Reputation: 6602
I'm looking for a way to add a dynamic property to a class (not an instance). Something like Django does with models' managers. Basically what I'm trying to achieve is this:
class Manager:
def __init__(self, table_name):
self.table_name = table_name
# rest omitted for brevity
class BaseModel:
# somehow create a new instance of Manager
# and send the init param based off BaseModel's child
# class table_name Meta property
class MyModel(BaseModel):
class Meta:
table_name = 'my_table'
MyModel.manager # should return an instance of Manager(table_name='my_table')
I've tried using the constructor (__new__
), but that obviously only works after I create at least an instance of MyModel
.
Upvotes: 2
Views: 62
Reputation: 36239
You can use __init_subclass__
for that purpose:
class BaseModel:
def __init_subclass__(cls):
cls.manager = Manager(cls.Meta.table_name)
Upvotes: 2