我可以创建一个派生自元类的子类吗?

2024-06-26 18:01:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个从超类中声明的元类继承的类,我是这样做的:

from sqlalchemy import Column, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker


class Database(object):
    """
        Class that holds all data models classes and functions
    """
    def __init__(self, wenDbPath = "test.db"):
        self.engine = create_engine('sqlite:///' + "c:/"+wenDbPath, echo=False)
        self.Session = sessionmaker(bind=self.engine)
        **self.Base** = declarative_base() # This returns a metaclass.
        self.Base.metadata.create_all(self.engine)
        self.session = self.Session()

    class Element(**self.Base**):
        __tablename__ = 'elements'
        idNumber = Column(String(255), primary_key=True)
        smallDiscription = Column(String(50), nullable=False)
        longDiscription = Column(String())
        webLink = Column(String())

        def __init__(self, idNumber, smallDiscription, longDiscription, webLink):
            self.idNumber = idNumber
            self.longDiscription = longDiscription
            self.smallDiscription = smallDiscription
            self.webLink = webLink
        def __repr__(self):
            return "<Element ('%s : %s')>" % (self.idNumber, self.smallDiscription)

Python给了我以下消息

class Element(self.Base): NameError: name 'self' is not defined

我怎么能做这样的事?你知道吗

先谢谢你。你知道吗


Tags: fromimportselfbasestringsqlalchemycreatecolumn
1条回答
网友
1楼 · 发布于 2024-06-26 18:01:15

类主体在运行__init__之前进行求值。由于Base不依赖于__init__参数,因此可以在类求值时对其求值:

class Database(object):
    ...
    Base = declarative_base() # This returns a metaclass.
    class Element(Base):
        ...

请注意,您将Base用作超类,而不是元类;元类语法是__metaclass__ = Base(metaclass=Base),具体取决于版本。见What is a metaclass in Python?

相关问题 更多 >