gpt4 book ai didi

python - 如何为从 sqlalchemy 声明性基扩展的类定义元类

转载 作者:太空狗 更新时间:2023-10-29 21:01:20 24 4
gpt4 key购买 nike

我使用:Python 2.6 和 sqlalchemy 0.6.1

这就是我想要做的:

from sqlalchemy.types import (
Integer,
String,
Boolean
)
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class SampleMeta(type):
def __new__(cls, name, bases, attrs):
attrs.update({ 'id': Column('Id', Integer, primary_key=True),
'name': Column('Name', String),
'description': Column('Description', String),
'is_active': Column('IsActive', Boolean)
})
return super(SampleMeta, cls).__new__(cls, name, bases, attrs)

class Sample(Base):
__tablename__ = 'Sample'
__table_args__ = {'useexisting': True}
__metaclass__ = SampleMeta

def __init__(self, id, name, description, is_active):
self.id = id
self.name = name
self.description = description
self.is_active = is_active

def __repr__(self):
return "<(%d, '%s', '%s', %r)>" % (self.id, self.name, self.description, self.isactive)

我得到的错误是这样的:

TypeError: Error when calling the metaclass bases
metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

现在,如果我使用

class Sample(object)

代替

class Sample(Base)

它工作得很好。

我需要动态更新类的属性。因此,我将使用动态属性和列名。我需要上面的代码才能到达那里。

请帮忙

最佳答案

要使用元类,在这种情况下它必须从 Declaratives DeclaredMeta 派生。但是这个用例不需要元类。使用 mixins :

from sqlalchemy.types import (
Integer,
String,
Boolean
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column

Base = declarative_base()

class SampleMixin(object):
id = Column("Id", Integer, primary_key=True)
name = Column("Name", String)
description = Column("Description", String)
is_active = Column("IsActive", Boolean)

class Sample(SampleMixin, Base):
__tablename__ = 'Sample'
__table_args__ = {'useexisting': True}

def __init__(self, id, name, description, is_active):
self.id = id
self.name = name
self.description = description
self.is_active = is_active

def __repr__(self):
return "<(%d, '%s', '%s', %r)>" % (self.id, self.name,
self.description, self.isactive)

from sqlalchemy import select
print select([Sample.id, Sample.name])

关于python - 如何为从 sqlalchemy 声明性基扩展的类定义元类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17438879/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com