The __init__
method defines what is done on creating an instance of a class. Can I do something equivalent when a subclass is created?
Let's say I have the abstract class Entity
:
class Entity:
def __onsubclasscreation__(cls):
for var in cls.__annotations__:
cls.__dict__[var] = property(lambda self:self.vars[var])
This would mean that whenever I define a new class inheriting from Entity
, all annotated variables of that class would receive a getter:
class Train(Entity):
wagons: int
color: str
>>> t = Train()
>>> t.vars["wagons"] = 5
>>> t.wagons
5
I can't do this on instantiation because properties need to be defined in the class, and I can't do it in the superclass because I don't know which attributes will be needed. Is there any way to do something dynamically on subclass creation?