Home  >  Q&A  >  body text

python - 关于修饰类 @class

看到文章 ( 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

请问什么会出错? 正确修饰类的应该如何使用?

天蓬老师天蓬老师2764 days ago558

reply all(2)I'll reply

  • 阿神

    阿神2017-04-17 14:45:44

    @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:

    #定义
    def decorator(C):
    #process class C
        return C
    
    #使用
    @decorator
    class C:...    
    

    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:

    def test(cls):
        class C():
    #   class C 的定义填在这里。 
        return C
    

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 14:45:44

    sy is a class. Implement the __call__ method.

     class Sy(object):
        value=32
    
        def __call__(self, _class):
            pass
    

    reply
    0
  • Cancelreply