Mam hierarchię obiektów, w której prawie wszystkie metody są metod klasy. Wygląda to tak:Python - czy mogę programowo dekorować metody klasy z instancji klasy?
class ParentObject(object):
def __init__(self):
pass
@classmethod
def smile_warmly(cls, the_method):
def wrapper(kls, *args, **kwargs):
print "-smile_warmly - "+kls.__name__
the_method(*args, **kwargs)
return wrapper
@classmethod
def greetings(cls):
print "greetings"
class SonObject(ParentObject):
@classmethod
def hello_son(cls):
print "hello son"
@classmethod
def goodbye(cls):
print "goodbye son"
class DaughterObject(ParentObject):
@classmethod
def hello_daughter(cls):
print "hello daughter"
@classmethod
def goodbye(cls):
print "goodbye daughter"
if __name__ == '__main__':
son = SonObject()
son.greetings()
son.hello_son()
son.goodbye()
daughter = DaughterObject()
daughter.greetings()
daughter.hello_daughter()
daughter.goodbye()
kodu jak podano wyjść następujące:
greetings
hello son
goodbye son
greetings
hello daughter
goodbye daughter
Chciałbym kod do wyjścia następuje:
-smile_warmly - SonObject
greetings
-smile_warmly - SonObject
hello son
-smile_warmly - SonObject
goodbye son
-smile_warmly - DaughterObject
greetings
-smile_warmly - DaughterObject
hello daughter
-smile_warmly - DaughterObject
goodbye daughter
ale nie chcę przed każdą metodą dodać linię @smile_warmly
(a gdy spróbuję to zrobić w powyższym kodzie, otrzymuję komunikat o błędzie TypeError: 'classmethod' object is not callable
). Przeciwnie, chciałbym, aby dekoracja każdej metody odbywała się programowo w metodzie __init__()
.
Czy można programowo dekorować metody w Pythonie?
EDIT: Znaleziono coś, co wydaje się działać - zobacz moją odpowiedź poniżej. Dzięki BrenBarn.
Czy pojęcie metaclasses znajomo? –
Wygląda na to, że będziesz chciał spojrzeć na to: http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python Być może, jeśli używasz dekoratorów również ten facet: http://stackoverflow.com/questions/739654/understanding-python-decorators –
Słyszałem o nich, ale o to chodzi. Więc nie. – jononomo