pythonpython-3.xpython-class

Automatically calling class function after init


I want to automate a class method which would be called right after __init__ has completed.

e.g,

class A:
    def __init__(self):
        initialization statement
    def post_init(self):
        #this should be automatically called after completion of __init__ function.
        some statement

How can I achieve this?


Solution

  • If you want to run post_init automatically after __init__ for this class and all inheriting classes you need to mess with how objects are instantiated using metaclasses. By default when you __call__ a class using A() it invokes a __new__ to create a new object and then an __init__ method of that object. You want to add the post_init to that sequence

    class MyMetaclass(type):
      def __call__(cls, *args, **kwargs):
        new_obj = type.__call__(cls, *args, **kwargs)
        new_obj.post_init()
        return new_obj
    
    class A(metaclass=MyMetaclass):
      def __init__(self):
        print('init called')
    
      def post_init(self):
        print('post init called')
    

    You can verify that

    >>> A()
    init called
    post init called
    <__main__A at 0x7f3988e2c6a0>