回答背景知识

这些都是装饰器(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. scrapy框架--新建调试的main.py文件

    一.原因: 由于pycharm中没有scrapy的一个模板,所有没办法直接在scrapy文件中调试,所有我们需要写一个自己的main.py文件,在文件里面调用命令行,来实现scrapy的一个调试.(在 ...

  2. MySQL事务的四种隔离级别

    事务的基本要素: 原子性(atomicity):事务开始后的全部操作, 要么全部执行成功,如果中间出现错误,事务回滚到事务开始前的状态. 一致性(Consistency):事务开始后,数据库的完整性约 ...

  3. asciinema.org -Record Your Terminal Share it with no fuss

    紀錄 Terminal 下指令的過程 http://asciinema.org/

  4. 如何使用 C++ Inja html template 模板

    C++ html template Inja是现代C ++的模板引擎,受到jinja for python的启发.它有一个简单而强大的模板语法,包含所有变量,循环,条件,包含,回调,您需要的注释,嵌套 ...

  5. Apache2.2学习笔记全集

    一.基本介绍 待补充... 二.Apache默认配置文件解释 # 定义apache运行的目录,即程序所在的位置 ServerRoot "/usr/local/apache2" # ...

  6. Node中的Cookie和Session

    1.Cookie HTTP是无状态协议.例:打开一个域名的首页,进而打开该域名的其他页面,服务器无法识别访问者.即同一浏览器访问同一网站,每次访问都没有任何关系. Cookie的原理是:客户端浏览器在 ...

  7. java 多线程 线程安全及非线程安全的集合对象

    一.概念: 线程安全:就是当多线程访问时,采用了加锁的机制:即当一个线程访问该类的某个数据时,会对这个数据进行保护,其他线程不能对其访问,直到该线程读取完之后,其他线程才可以使用.防止出现数据不一致或 ...

  8. Feign基础教程

    https://blog.csdn.net/u010862794/article/details/73649616 简介 Feign使得 Java HTTP 客户端编写更方便.Feign 灵感来源于R ...

  9. RFCN理解,不完整待补全

    RFCN的核心是通过修改roi pooling的位置,来增加共享参数的层,减少运算时间: roi pooling位置的影响如下: 越靠近 Input - 对应 ROI-Wise 检测子网越深,准确度也 ...

  10. js unshift()

    定义与用法 unshift()方法可像数组添加一个或多个元素 并返回新长度 语法 arrayObject.unshift(newElement1,newElement2,......,newEleme ...