0

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?

5
  • call self.post_init() inside __init__, but if you are not passing any extra args to .post_init, why can't use all statements inside __init__? Commented Aug 28, 2023 at 13:29
  • post_init() is a time consuming function and takes a while to complete.and the class is to be instantiated inside another class as a property. So if i use it inside init() then I am unable to instantiate the class untill both methods have completed execution. Commented Aug 28, 2023 at 13:39
  • what i want is instantiate the class with init() and then call the second function. Commented Aug 28, 2023 at 13:40
  • Do you want to call the second function in background and call the dependent functions after the background task completes? Commented Aug 28, 2023 at 13:43
  • Do it matter? If you instantiate and you cannot wait the finish of post_init, I assume you are doing multithread, but so you have a incomplete class, so you can have bugs. Often you just have a status __is_fully_initialized, and you check at every function call. In case of need you do post_init(). (this trick is used on such slow case: doing work only when needed) Commented Aug 28, 2023 at 13:43

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.