的这不起作用:Python的 - 装饰 - 试图访问父类的方法
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 2010-10-07 20:06:41