我试图创建一个继承自超类中声明的元类的类,我确实喜欢这样:
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:名称'self'未定义
我该怎么办?
提前谢谢你。
答案 0 :(得分:0)
在__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?