python subclass __init__ code example
Example 1: python __init_subclass__
In [16]: class Foo:
...: def __init_subclass__(cls):
...: print('ok')
...: print(cls.att)
In [17]: class SubFoo(Foo):
...: att = 1
...: pass
...:
ok
1
Example 2: python __init_subclass__
class Philosopher:
def __init_subclass__(cls, default_name, **kwargs):
super().__init_subclass__(**kwargs)
print(f"Called __init_subclass({cls}, {default_name})")
cls.default_name = default_name
class AustralianPhilosopher(Philosopher, default_name="Bruce"):
pass
class GermanPhilosopher(Philosopher, default_name="Nietzsche"):
default_name = "Hegel"
print("Set name to Hegel")
Bruce = AustralianPhilosopher()
Mistery = GermanPhilosopher()
print(Bruce.default_name)
print(Mistery.default_name)