Python metaclass to run a class method automatically on derived class
Posted
by
Barry Steyn
on Stack Overflow
See other posts from Stack Overflow
or by Barry Steyn
Published on 2012-06-21T02:57:22Z
Indexed on
2012/06/21
3:16 UTC
Read the original article
Hit count: 160
I want to automatically run a class method defined in a base class on any derived class during the creation of the class. For instance:
class Base(object):
@classmethod
def runme():
print "I am being run"
def __metclass__(cls,parents,attributes):
clsObj = type(cls,parents,attributes)
clsObj.runme()
return clsObj
class Derived(Base):
pass:
What happens here is that when Base is created, ''runme()'' will fire. But nothing happens when Derived is created.
The question is: How can I make ''runme()'' also fire when creating Derived.
This is what I have thought so far: If I explicitly set Derived's metclass to Base's, it will work. But I don't want that to happen. I basically want Derived to use the Base's metaclass without me having to explicitly set it so.
© Stack Overflow or respective owner