gpt4 book ai didi

python - 从父类(super class)实例化子类

转载 作者:太空宇宙 更新时间:2023-11-03 18:32:17 27 4
gpt4 key购买 nike

我有以下 python 代码,它使用 SQLAlchemy 在 MySQL 数据库中创建多态结构。

class Animal(Base):
key = Column(Integer(), Sequence("My Counter" ,1 ,1), primary_key = True)
name = Column(String())
discriminator = Column('type',String())
__mapper_args__ = {'polymorphic_on':discriminator}

def __init__(self,key,name):
self.key = key
self.name = name

class Cat(Animal):
__tablename__ = 'cat'
__mapper_args__ = {'polymorphic_identity':'cat'}
def walk():
pass

class Dog(Animal):
__tablename__ = 'dog'
__mapper_args__ = {'polymorphic_identity':'dog'}

def walk():
pass

我想知道加载它的最佳方法是什么:

a = Animal(key=1)
c = a.create()

c 现在将是 Cat 或 Dog 对象,具体取决于它的类型。 Animal 表包含此信息。

谢谢

最佳答案

这不是使用 sqlalchemy 查询数据库的方式。为了获得特定 key 的动物,您需要做的就是执行:

my_key = 1
a = session.query(Animal).get(my_key)
# sqlalchemy will figure out the type automatically and will return object of proper class
assert type(a) in (Cat, Dog,)

请注意,您提供的模型不完整。下面的模型应该是完整的工作模型:

class Animal(Base):
__tablename__ = 'animal'
key = Column(Integer(), Sequence("My Counter" ,1 ,1), primary_key = True)
name = Column(String())
discriminator = Column('type',String())
__mapper_args__ = { 'polymorphic_on':discriminator, }

def __init__(self,key,name):
self.key = key
self.name = name

class Cat(Animal):
__tablename__ = 'cat'
__mapper_args__ = {'polymorphic_identity':'cat'}
key = Column(Integer(), ForeignKey('animal.key'), primary_key = True)

def walk(self):
print "cat walking"

class Dog(Animal):
__tablename__ = 'dog'
__mapper_args__ = {'polymorphic_identity':'dog'}
key = Column(Integer(), ForeignKey('animal.key'), primary_key = True)

def walk(self):
print "dog walking"

关于python - 从父类(super class)实例化子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22215250/

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