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

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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