2

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.

Eduard Luca
  • 6,514
  • 16
  • 85
  • 137
  • See [Is there a way to call a method on definition of a subclass in Python?](https://stackoverflow.com/q/57151233/674039) – wim Nov 15 '19 at 22:28

1 Answers1

2

You can use __init_subclass__ for that purpose:

class BaseModel:
    def __init_subclass__(cls):
        cls.manager = Manager(cls.Meta.table_name)
a_guest
  • 34,165
  • 12
  • 64
  • 118