Это не работает: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
декораторов как фильм Inception; чем больше уровней у вас, тем больше они запутываются. Я пытаюсь получить доступ к классу, который определяет метод (во время определения), чтобы я мог установить атрибут (или изменить атрибут) класса.
Version 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