1

Есть код

class ModelMeta(type):
    def __new__(cls, name, bases, namespace, table=False, **kwargs):
        def init(self, *args):
            for field, value in zip(namespace["__annotations__"], args):
                setattr(self, field, value)

        namespace["__init__"] = init
        return super().__new__(cls, name, bases, namespace)


class Model(metaclass=ModelMeta):
    @classmethod
    def get_tablename(cls):
        tablename = cls.__name__.lower()
        if hasattr(cls, '__tablename__'):
            tablename = getattr(cls, '__tablename__')
        return tablename


class User(Model, table=True):
    __tablename__ = 'users'
    username: str
    password: str
    age: int

При создании новой модели можно указать параметр table, который мне нужен в классе Model, чтобы исходя из состояний этого параметра (True или False) писать разную логику.

Как получить доступ к параметру table мета-класса ModelMeta из класса Model.

Спасибо.

1 ответ 1

2

В методе __new__ сохраните в атрибут класса:

class ModelMeta(type):
    def __new__(cls, name, bases, namespace, table=False, **kwargs):
        def init(self, *args):
            for field, value in zip(namespace["__annotations__"], args):
                setattr(self, field, value)

        namespace["__init__"] = init
        namespace["_table"] = table
        return super().__new__(cls, name, bases, namespace)


class Model(metaclass=ModelMeta):
    @classmethod
    def get_tablename(cls):
        tablename = cls.__name__.lower()
        if hasattr(cls, '__tablename__'):
            tablename = getattr(cls, '__tablename__')
        return tablename

    def get_table(self):
        return self._table

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.