今天看别人的代码遇到了@property,让我不由想起Java中的注解,难道Python中也有这东西?
def deco(func): .......
@deco def foo(): pass
foo=deco(foo)
def deco(args): ......
@deco(args) def foo(): pass
foo = deco(args)(foo)
@deco1 @deco2 def foo(): pass
foo = deco1(deco2(foo))
@deco1 @deco2(args) def foo(): pass
foo = deco1(deco2(args)(foo))
from time import ctime def printCallTime(func): def decoratedFunc(): print '[%s] %s() is called.' % (ctime(),func.__name__) func() return decoratedFunc@printCallTime
def myFunc():
passmyFunc()
[Fri Mar 08 13:23:27 2013] myFunc() is called.
class Parrot(object): def __init__(self): self._voltage = 100000@property def voltage(self): """Get the current voltage.""" return self._voltage</pre>
@voltage.setter def voltage(self, value): self._voltage = value
new-style classAny class which inherits from . This includes all built-in types like and . Only new-style classes can use Python’s newer, versatile features like , descriptors, properties, and .
-
也就是说继承自object的类才是new-style class 而且只有new-style class 才能设置属性,也即是说使用@property的时候,所在的类必须是继承自object的。
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于