gpt4 book ai didi

python - 在 Python 中从基类对象创建对象

转载 作者:太空宇宙 更新时间:2023-11-04 09:18:33 25 4
gpt4 key购买 nike

我有一个基类:

class Animal(object):
def __init__(self, name=None, food=None):
self.name = name
self.food = food

def eat(self):
print "The %s eats some %s" % (self.name, self.food)

还有一个扩展它的类:

class Pet(Animal):
def pet(self):
print "You pet the %s." % self.name
def feed(self):
print "You put some %s into the bowl." % self.food
self.eat()

假设我有一个 Animal 对象,它是这样创建的:

>>> fluffy_as_animal = Animal('dog', 'kibbles')

在 python 中是否有直接的方法从 fluffy_as_animal 创建一个 Pet 对象,而不是实际写出:

>>>> fluffy_as_pet = Pet(fluffy_as_animal.name, fluffy_as_animal.food)

更新

我做这个实现的原因是我有一个带有函数的类,该函数返回一组 Animal 类型的对象,所有我想实际用作 Pet对象:

class AnimalStore(object):
def fetch(count, query=None, server=None, *args, **kwargs):
connection = connect_to_server(server)
resp = connection.fetch_animals(query)
objects = parse_response(resp)
animals = []
for a in objects[:count]:
animals.append(Animal(a['name'], a.['food']))
return animals

class PetStore(AnimalStore):
def fetch(count, query=None, server=None, *args, **kwargs):
query = 'type=pet AND %s' % query
animals = super(PetFactory, self).fetch(count, query, server, *args, **kwargs)
pets = []
for animal in animals:
pets.append(magic_function(animal))
return pets

AnimalStorePetStore 位于不同的模块中。 AnimalStore 是标准 Animal API 的一部分,不会改变。基本上,我想通过使用与动物相同的机制获取宠物列表来扩展 Animal API,并且我希望能够利用 Animal 的所有其他内置功能API 已经提供了它的 AnimalAnimalStore 类。

最佳答案

您可以为 Pet 编写 __init__() 以接受 Animal 的实例(或者实际上,任何具有必要属性的对象 - - 鸭子打字!)以及个人属性。然后你可以做 fluffy_as_pet = Pet(fluffy_as_animal)。或者提供一个类方法(例如 Pet.from_object())来执行相同的操作,如果您不想重载 __init__()。即使您不控制 AnimalPet 类,您也可以创建它们自己的子类,它们的行为符合您的需要。

但是,最好更进一步,不要编写接受Animal 但不接受Pet 的代码。那么你不必转换它。同样,鸭子类型——如果对象具有正确的属性,则无论其类型如何,您都可以使用它。

关于python - 在 Python 中从基类对象创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5516263/

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