这是我的代码:
def a():
print 'sss'
@a()
def b():
print 'aaa'
b()
Run Code Online (Sandbox Code Playgroud)
跟踪是:
sss
Traceback (most recent call last):
File "D:\zjm_code\a.py", line 8, in <module>
@a()
TypeError: 'NoneType' object is not callable
Run Code Online (Sandbox Code Playgroud)
那么如何使用'@'
谢谢
更新
class a:
@property
def b(x):
print 'sss'
aa=a()
print aa.b
Run Code Online (Sandbox Code Playgroud)
它打印:
sss
None
Run Code Online (Sandbox Code Playgroud)
如何使用@property
谢谢
updated2
和类方法:
class a:
@classmethod
def b(x):
print 'sss'
aa=a()
print aa.b
Run Code Online (Sandbox Code Playgroud)
它打印:
<bound method classobj.b of <class __main__.a at 0x00B2DC00>>
Run Code Online (Sandbox Code Playgroud)
装饰器需要是一个可调用的对象(一个函数或一个实现__call__的对象),其中参数是已经装饰的函数,结果是一个函数,它将替换已经装饰的函数,因此,使用打印'sss'而不是打印'aaa'的示例:
>>> def a(f): ... def replacementfunc(): ... print 'sss' ... return replacementfunc; ... >>> @a ... def b(): ... print 'aaa' ... >>> b() sss
或者,更详细的例子:
>>> class print_decorator(object):
... def __init__(self,text):
... self.text = text;
... def __call__(self,f):
... def replacement():
... print self.text;
... return replacement;
...
>>> @print_decorator("Hello world!")
... def b():
... print 'aaa';
...
>>> b()
Hello world!
编辑
至于您更新的问题,您需要查看@property的文档.目前尚不清楚你想要完成什么,虽然我的猜测是你想要的:
class a:
@property
def b(self):
return 'sss'
aa=a()
print aa.b # prints 'sss', whereas without @property, prints <function ... >
| 归档时间: |
|
| 查看次数: |
1496 次 |
| 最近记录: |