我有一个对象层次结构,其中几乎所有方法都是类方法。它如下所示:
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()
给定的代码输出以下内容:
greetings
hello son
goodbye son
greetings
hello daughter
goodbye daughter
我希望代码输出以下内容:
-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
但我不想@smile_warmly
在每个方法之前添加这一行(当我尝试在上面的代码中这样做时,我收到错误消息TypeError: 'classmethod' object is not callable
)。相反,我希望每个方法的装饰在方法中以编程方式进行__init__()
。
是否可以在 Python 中以编程方式装饰方法?
编辑:发现了一些似乎有效的东西——见下面我的回答。感谢布伦巴恩。