'Automatically call method after __init__ in child class
I have the following code:
class Parent:
def __init__(self) -> None:
print(f"init Parent")
class Child(Parent):
def __init__(self) -> None:
super().__init__()
print(f"init Child")
def post_init(self):
print(f"post init")
Child()
Here I get the output:
init Parent
init Child
Is it possible to modify the code in the Parent-class to call the post_init method from the Child-class automatically after the ___init___() of the Parent and the Child-class. I would like to have the following output:
init Parent
init Child
post init
I don't want to modify the Child-class!!! I have already tried to define a decorator in the Parent-class, but I failed.
EDIT:
The Parent-class is a pattern-class and is multiple used in multiple children. So I don't want to take care every time i use the Child-class. Is it possible on using the abstract-package?
Solution 1:[1]
You can also write code like this:
class Meta(type):
def __call__(cls, *args, **kwargs):
instance = super().__call__(*args, **kwargs)
instance.post_init()
return instance
class Parent(metaclass=Meta):
def __init__(self) -> None:
print(f"init Parent")
class Child(Parent):
def __init__(self) -> None:
super().__init__()
print(f"init Child")
def post_init(self):
print(f"post init")
Child()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | quasi-human |
