Calling a class method when creating Python classes

I would like to automatically run some code when creating a class that can call other methods of the class. I did not find a way to do this from the class declaration itself, and as a result I create @classmethod, called __clsinit__, and will call it from the scope immediately after the class declaration. Is there a way that I can define so that it is automatically called after creating the class object?

+5
source share
1 answer

You can do this using a metaclass or class decorator .

The class decorator (since version 2.6) is probably easier to understand:

def call_clsinit(cls):
    cls._clsinit()
    return cls

@call_clsinit
class MyClass:
    @classmethod
    def _clsinit(cls):
        print "MyClass._clsinit()"

; , (, ):

def call_clsinit(*args, **kwargs):
    cls = type(*args, **kwargs)
    cls._clsinit()
    return cls;

class MyClass(object):
    __metaclass__ = call_clsinit

    @classmethod
    def _clsinit(cls):
        print "MyClass._clsinit()"
+10

All Articles