繁体   English   中英

使用装饰器保存所有类方法

[英]Save all class methods with decorator

我有一个类,并且我希望所有类的方法都在该类内的列表中,即使我有两个同名的方法,我也希望它能工作,但我的问题是我无法访问该类以将方法放在那里。 可以说我有装饰师

def dec(func):
    class = ????
    class.methods.append(func)
    return func

我有课

class A(object):
    methods = []
    @dec
    def a(self):
       print 2
    @dec
    def a(self):
       print 3

我想能够做

A.methods[0](A())
A.methods[1](A())
(A() becuase those methods need self)

或类似的东西

我已经读过很多这样的问题,并且看起来好像不是我真正想要的,因为在调用装饰器时A不存在,但是也许有一种方法可以访问它的变量,因为装饰器在其中运行?

类对象本身仅 body语句( class <classname>(<bases,>):块内的所有语句均已执行class <classname>(<bases,>): 之后构造另一方面,装饰器与它们要修饰的函数一起执行。

您可以在想要将方法添加到装饰器的列表中:

class A(object):
    methods = []
    @dec(methods)
    def a(self):
        print 2
    @dec(methods)
    def a(self):
        print 3

并让装饰器使用该列表来追加您的方法:

def dec(methodslist):
    def decorator(f):
        methodslist.append(f)
        return f
    return decorator

如果您使用的是Python 3,则另一个选择是让您使用带有自定义metaclass.__prepare__类方法使用collections.defaultdict()首先将所有属性收集到列表中,因此即使命名相同,也仍然可以访问它们。 然后,您的装饰器只需用额外的属性或其他东西“标记”每个功能对象。 这涉及更多。

然后,当您要调用这些函数时,很正确的一点是它们没有绑定,也不会为您传递self 手动传递self或手动绑定 函数是描述符对象 ,调用它们的__get__方法将它们绑定到实例:

for func in self.methods:
    method = func.__get__(self)
    method()

演示:

>>> def dec(methodslist):
...     def decorator(f):
...         methodslist.append(f)
...         return f
...     return decorator
...
>>> class A(object):
...     methods = []
...     @dec(methods)
...     def a(self):
...         print 2
...     @dec(methods)
...     def a(self):
...         print 3
...     def call_all(self):
...         for func in self.methods:
...             method = func.__get__(self)
...             method()
...
>>> A().call_all()
2
3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM