我试图创建一个从超类中声明的元类继承的类,我是这样做的:
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
我怎么能做这样的事?你知道吗
先谢谢你。你知道吗
类主体在运行
__init__
之前进行求值。由于Base
不依赖于__init__
参数,因此可以在类求值时对其求值:请注意,您将
Base
用作超类,而不是元类;元类语法是__metaclass__ = Base
或(metaclass=Base)
,具体取决于版本。见What is a metaclass in Python?相关问题 更多 >
编程相关推荐