看到文章 ( http://mp.weixin.qq.com/s?__biz=MjM5NzU0MzU0Nw==&mid=206275292&idx=1&sn=245ffc6b543c323adc4ed8ac54942e24&scene=5#rd)
修饰类部分,
[1]装饰器无参数:
a.被装饰对象无参数:
1 >>> def test(cls):
2 def _test():
3 clsName=re.findall("(w+)",repr(cls))[-1]
4 print "Call %s.__init()."%clsName
5 return cls()
6 return _test
7
8 >>> @test
9 class sy(object):
10 value=32
11
12
13 >>> s=sy()
14 Call sy.__init().
15 >>> s
16 <__main__.sy object at 0x0000000002C3E390>
17 >>> s.value
18 32
19 >>>
在我的环境 执行出错.
提示
TypeError: 'sy' object is not callable
py版本如下
$ python -V
Python 2.7.9
请问什么会出错? 正确修饰类的应该如何使用?
@Uncommonly used nickname. Let me tell you, welcome to discuss
If I understand correctly, the original English name of Decoration class in the original post "2. Decoration class: the object to be decorated is a class" should be Class Decorators.
According to the syntax requirements, the format of class decorators is as follows:
Reference material "Learning Python 5E" page1277-1278
So, the definition of class decorator in the question is completely wrong.
It should be in the following form:
sy
is aclass
. Implement the__call__
method.