ほとんどすべてのメソッドがクラスメソッドであるオブジェクト階層があります。次のようになります。
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に感謝します。