Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a class method upon creation of Python classes

I'd like to automatically run some code upon class creation that can call other class methods. I have not found a way of doing so from within the class declaration itself and end up creating a @classmethod called __clsinit__ and call it from the defining scope immediately after the class declaration. Is there a method I can define such that it will get automatically called after the class object is created?

like image 549
Simon Avatar asked Aug 24 '12 19:08

Simon


People also ask

How do you call a class method in a class Python?

To call a class method, put the class as the first argument. Class methods can be can be called from instances and from the class itself. All of these use the same method. The method can use the classes variables and methods.

How do you call a class method from another class method in Python?

Call method from another class in a different class in Python. we can call the method of another class by using their class name and function with dot operator. then we can call method_A from class B by following way: class A: method_A(self): {} class B: method_B(self): A.

Can you call the base class method without creating an instance in Python?

Static method can be called without creating an object or instance. Simply create the method and call it directly. This is in a sense orthogonal to object orientated programming: we call a method without creating objects.


1 Answers

You can do this with a metaclass or a class decorator.

A class decorator (since 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()"

Metaclasses are more powerful; they can call code and modify the ingredients of the class before it is created as well as afterwards (also, they can be inherited):

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()"
like image 62
ecatmur Avatar answered Oct 20 '22 22:10

ecatmur