这行不通:
def register_method(name=None):
def decorator(method):
# The next line assumes the decorated method is bound (which of course it isn't at this point)
cls = method.im_class
cls.my_attr = 'FOO BAR'
def wrapper(*args, **kwargs):
method(*args, **kwargs)
return wrapper
return decorator
装饰器就像电影盗梦空间;您进入的级别越多,它们就越困惑。我正在尝试访问定义方法的类(在定义时),以便我可以设置该类的属性(或更改属性)。
版本 2 也不起作用:
def register_method(name=None):
def decorator(method):
# The next line assumes the decorated method is bound (of course it isn't bound at this point).
cls = method.__class__ # I don't really understand this.
cls.my_attr = 'FOO BAR'
def wrapper(*args, **kwargs):
method(*args, **kwargs)
return wrapper
return decorator
当我已经知道它为什么损坏时,将我损坏的代码放在上面的意义在于它传达了我正在尝试做的事情。
最佳答案
我不认为你可以用装饰器做你想做的事(快速编辑:无论如何,使用方法的装饰器)。构造方法时会调用装饰器,在构造类之前。您的代码无法正常工作的原因是调用装饰器时该类不存在。
jldupont 的评论是要走的路:如果你想设置类的属性,你应该装饰类或使用元类。
编辑:好的,看到您的评论后,我可以想到一个可能适合您的两部分解决方案。使用方法的装饰器设置方法的属性,然后使用元类搜索具有该属性的方法并设置类的适当属性:
def TaggingDecorator(method):
"Decorate the method with an attribute to let the metaclass know it's there."
method.my_attr = 'FOO BAR'
return method # No need for a wrapper, we haven't changed
# what method actually does; your mileage may vary
class TaggingMetaclass(type):
"Metaclass to check for tags from TaggingDecorator and add them to the class."
def __new__(cls, name, bases, dct):
# Check for tagged members
has_tag = False
for member in dct.itervalues():
if hasattr(member, 'my_attr'):
has_tag = True
break
if has_tag:
# Set the class attribute
dct['my_attr'] = 'FOO BAR'
# Now let 'type' actually allocate the class object and go on with life
return type.__new__(cls, name, bases, dct)
就是这样。使用如下:
class Foo(object):
__metaclass__ = TaggingMetaclass
pass
class Baz(Foo):
"It's enough for a base class to have the right metaclass"
@TaggingDecorator
def Bar(self):
pass
>> Baz.my_attr
'FOO BAR'
不过,老实说?使用 supported_methods = [...]
方法。元类很酷,但是在您之后必须维护您的代码的人可能会讨厌您。
关于Python - 装饰器 - 试图访问方法的父类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3885459/