I have an object hierarchy in which almost all of the methods are class methods. It looks like the following:
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()
The code as given outputs the following:
greetings
hello son
goodbye son
greetings
hello daughter
goodbye daughter
I would like the code to output the following:
-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
But I don't want to add the line @smile_warmly
before each method (and when I try to do that in the code above, I get error message TypeError: 'classmethod' object is not callable
). Rather, I would like the decoration of each method to take place programmatically in the __init__()
method.
Is it possible to programmatically decorate methods in Python?
EDIT: Found something that seems to work -- see my answer below. Thanks to BrenBarn.