【发布时间】:2010-10-07 20:05:02
【问题描述】:
这不起作用:
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
当我已经知道它为什么会损坏时,将损坏的代码放在上面的目的是它传达了我想要做的事情。
【问题讨论】:
-
和制作一个元类没有帮助?