【发布时间】:2012-12-15 06:14:09
【问题描述】:
我有一个对象层次结构,其中几乎所有的方法都是类方法。如下所示:
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 中以编程方式装饰方法?
编辑:找到了一些似乎可行的东西——请参阅下面的答案。感谢 BrenBarn。
【问题讨论】:
-
元类的概念你熟悉吗?
-
听起来你会想看看这个:stackoverflow.com/questions/100003/… 如果你也打算使用装饰器,那么这个人:stackoverflow.com/questions/739654/…
-
我听说过它们,但仅此而已。所以没有。
标签: python decorator class-method