回答背景知识

这些都是装饰器(decorator)。装饰器是一种特殊的函数,要么接受函数作为输入参数,并返回一个函数,要么接受一个类作为输入参数,并返回一个类。

@标记是语法糖(syntactic sugar),可以让你以简单易读得方式装饰目标对象。

@my_decorator
def my_func(stuff):
do_things
Is equivalent to def my_func(stuff):
do_things my_func = my_decorator(my_func)

你可以在本网站上找到介绍装饰器工作原理的教材。

真正的答案

@classmethod@staticmethod@property这三个装饰器的使用对象是在类中定义的函数。下面的例子展示了它们的用法和行为:

class MyClass(object):
def __init__(self):
self._some_property = "properties are nice"
self._some_other_property = "VERY nice"
def normal_method(*args,**kwargs):
print "calling normal_method({0},{1})".format(args,kwargs)
@classmethod
def class_method(*args,**kwargs):
print "calling class_method({0},{1})".format(args,kwargs)
@staticmethod
def static_method(*args,**kwargs):
print "calling static_method({0},{1})".format(args,kwargs)
@property
def some_property(self,*args,**kwargs):
print "calling some_property getter({0},{1},{2})".format(self,args,kwargs)
return self._some_property
@some_property.setter
def some_property(self,*args,**kwargs):
print "calling some_property setter({0},{1},{2})".format(self,args,kwargs)
self._some_property = args[0]
@property
def some_other_property(self,*args,**kwargs):
print "calling some_other_property getter({0},{1},{2})".format(self,args,kwargs)
return self._some_other_property o = MyClass()
# 未装饰的方法还是正常的行为方式,需要当前的类实例(self)作为第一个参数。 o.normal_method
# <bound method MyClass.normal_method of <__main__.MyClass instance at 0x7fdd2537ea28>> o.normal_method()
# normal_method((<__main__.MyClass instance at 0x7fdd2537ea28>,),{}) o.normal_method(1,2,x=3,y=4)
# normal_method((<__main__.MyClass instance at 0x7fdd2537ea28>, 1, 2),{'y': 4, 'x': 3}) # 类方法的第一个参数永远是该类 o.class_method
# <bound method classobj.class_method of <class __main__.MyClass at 0x7fdd2536a390>> o.class_method()
# class_method((<class __main__.MyClass at 0x7fdd2536a390>,),{}) o.class_method(1,2,x=3,y=4)
# class_method((<class __main__.MyClass at 0x7fdd2536a390>, 1, 2),{'y': 4, 'x': 3}) # 静态方法(static method)中除了你调用时传入的参数以外,没有其他的参数。 o.static_method
# <function static_method at 0x7fdd25375848> o.static_method()
# static_method((),{}) o.static_method(1,2,x=3,y=4)
# static_method((1, 2),{'y': 4, 'x': 3}) # @property是实现getter和setter方法的一种方式。直接调用它们是错误的。
# “只读”属性可以通过只定义getter方法,不定义setter方法实现。 o.some_property
# 调用some_property的getter(<__main__.MyClass instance at 0x7fb2b70877e8>,(),{})
# 'properties are nice'
# “属性”是很好的功能 o.some_property()
# calling some_property getter(<__main__.MyClass instance at 0x7fb2b70877e8>,(),{})
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: 'str' object is not callable o.some_other_property
# calling some_other_property getter(<__main__.MyClass instance at 0x7fb2b70877e8>,(),{})
# 'VERY nice' # o.some_other_property()
# calling some_other_property getter(<__main__.MyClass instance at 0x7fb2b70877e8>,(),{})
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: 'str' object is not callable o.some_property = "groovy"
# calling some_property setter(<__main__.MyClass object at 0x7fb2b7077890>,('groovy',),{}) o.some_property
# calling some_property getter(<__main__.MyClass object at 0x7fb2b7077890>,(),{})
# 'groovy' o.some_other_property = "very groovy"
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# AttributeError: can't set attribute o.some_other_property
# calling some_other_property getter(<__main__.MyClass object at 0x7fb2b7077890>,(),{})

本文首发于Python黑洞网,博客园同步跟新

python面试题之下面这些是什么意思:@classmethod, @staticmethod, @property?的更多相关文章

  1. Python类中装饰器classmethod,staticmethod,property,

    @classmethod 有的时候在类中会有一种情况,就是这个方法并不需要使用每一个对象属性 因此 这个方法中的self参数一个完全无用的参数,使用classmethod class A: __cou ...

  2. 最新Python笔试题2017 涵盖知识面广泛

    引言 想找一份Python开发工作吗?那你很可能得证明自己知道如何使用Python.下面这些问题涉及了与Python相关的许多技能,问题的关注点主要是语言本身,不是某个特定的包或模块.每一个问题都可以 ...

  3. 转--python 面试题

    # 每一题都值得好好琢磨钻透 [原文地址](http://www.cnblogs.com/Allen-rg/p/7693394.html)1.Python是如何进行内存管理的? 答:从三个方面来说,一 ...

  4. Python面试题 —— 获取列表中位数

    中位数是一个可将数值集合划分为相等的上下两部分的一个数值.如果列表数据的个数是奇数,则列表中间那个数据就是列表数据的中位数:如果列表数据的个数是偶数,则列表中间那2个数据的算术平均值就是列表数据的中位 ...

  5. python公司面试题集锦 python面试题大全

    问题一:以下的代码的输出将是什么? 说出你的答案并解释. class Parent(object): x = 1 class Child1(Parent): pass class Child2(Par ...

  6. 【Python】【面试必看】Python笔试题

    前言 现在面试测试岗位,一般会要求熟悉一门语言(python/java),为了考验求职者的基本功,一般会出 2 个笔试题,这些题目一般不难,主要考察基本功.要是给你一台电脑,在编辑器里面边写边调试,没 ...

  7. Python面试题整理-更新中

    几个链接: 编程零基础应当如何开始学习 Python ? - 路人甲的回答 网易云课堂上有哪些值得推荐的 Python 教程? - 路人甲的回答 怎么用最短时间高效而踏实地学习 Python? - 路 ...

  8. python 面试题4

    Python面试题 基础篇 分类: Python2014-08-08 13:15 2071人阅读 评论(0) 收藏 举报 最近,整理了一些python常见的面试题目,语言是一种工具,但是多角度的了解工 ...

  9. 一道Python面试题

    无意间,看到这么一道Python面试题:以下代码将输出什么? def testFun():    temp = [lambda x : i*x for i in range(4)]    return ...

随机推荐

  1. Python快速设置Excel表格边框

    import xlwings as xw #打开存好的excel app = xw.App() #设置应用 wb = xw.Book("E:/Data/小蜜蜂超市销售报表.xlsx" ...

  2. luoguP1313 计算系数 题解(NOIP2011)

    P1313 计算系数 题目 #include<iostream> #include<cstdlib> #include<cstdio> #include<cm ...

  3. Python:我可以使用类变量作为线程锁吗?

    我正在考虑使用类变量作为线程锁,因为我不想在全局变量中定义锁并且还想防止死锁.这实际上有用吗?例: import threading class A(object): lock = threading ...

  4. Eclipse连接MySQL数据库(傻瓜篇)

    我的环境:MySQL:mysql-essential-5.1.51-win32 jdbc驱动:我已经上传到csdn上一个:http://download.csdn.net/source/3451945 ...

  5. 向服务器发送post请求

    /** * 通过HttpClient发送Post请求 * @param path 请求路径 * @param params 请求参数 * @param encoding 编码 * @return 请求 ...

  6. c# 编程--结构体

    结构体:由多种简单类型,组合成一种复杂的类型.使用这种复杂的类型来解决生活中的实际例子. 一.结构体定义:struct 结构体的名子{    public 类型名 变量名;    .....}    ...

  7. redis 分布式锁的正确实现方式

    前言 分布式锁一般有三种实现方式:1. 数据库乐观锁:2. 基于Redis的分布式锁:3. 基于ZooKeeper的分布式锁.本篇博客将介绍第二种方式,基于Redis实现分布式锁.虽然网上已经有各种介 ...

  8. C# IOC DI 学习

    之前一直不理解IOC DI,今天使劲研究了下,感觉朦朦胧胧有点感觉了,网上的这篇文章对我的有很大的启发 http://www.cnblogs.com/jin-yuan/p/3823559.html 我 ...

  9. vue-axios请求

    <template> <div> <div v-if="!repoUrl">loding</div> <div v-else& ...

  10. ReactNative 遇到的问题汇总

    1.react-native 启动项目出现如下报错 解决方法: nvm install v9.0.0 nvm alias default v9.0.0