我希望在我的类中有一个方法,从用户输入中创建新的对象,并将它们添加到字典中(这可能不是最好的方法,请欣赏任何输入)。此外,对于其他函数,我仍然希望能够以简单的方式获得字典中对象的属性,这对我来说是最困难的部分。
我四处寻找类似的问题,但似乎找不到任何问题,而这个问题对我来说似乎相当笼统,我相信有一个简单的方法可以做到这一点,或者我只是做了一些非常错误的事情。如果我只是将对象添加到字典中,我只需要对象的“位置”,但是我希望根据名称和种类添加到字典中的特定属性,如下所示。
animals = {}
class animal:
def __init__(self,name,species):
self.name = name
self.species = species
def dict(self,name,species):
#i want this function to create and add new objects to animals 对于给定的名称和物种的用户输入,我希望dict()的输出将新对象添加到字典中,然后以某种方式遍历字典中所有动物的名称。提前谢谢你。
发布于 2019-05-15 15:18:07
我不知道您为什么要这样做,但是您可以使用类方法有效地创建一个新的构造函数,该构造函数也包含一个字典并在其中修改该字典。
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
@classmethod
def init_and_track(cls, dict_, name, species):
a = cls(name, species)
dict_[name] = a并按此使用
animals = {}
Animal.init_and_track(animals, 'sally', 'horse')至于获取用户输入,您可以执行以下操作
@classmethod
def init_and_track(cls, dict_):
name = input('name: ')
species = input('species: ')
a = cls(name, species)
dict_[name] = a其中,名称和种类是由用户在调用此方法时生成的。我不知道你到底想要什么,为什么要这样,但我相信这是你想要的。
你的评论表明你最初的问题是一个-problem --这样的问题怎么样?使用dataclasses定义您的动物,因为它只是一些数据的持有者(假设python3.7)
from dataclasses import dataclass
@dataclass
class Animal:
name: str
species: str
def say_hi(self):
print(f'{self.name} the {self.species} says hi')您看到的: <...>是注解类型。然后定义一个新的类来跟踪这些动物。
class Zoo:
def __init__(self):
self.animals = []
def add_animal(self):
print('adding a new animal to the zoo')
name = input('what is it\'s name? ')
species = input('what species is it? ')
a = Animal(name, species)
self.animals.append(a)
def find_by_name(self, name):
animals_with_name = [a for a in self.animals if a.name == name]
return animals_with_name
def find_by_species(self, species):
return [a for a in self.animals if a.species = species]如果您只想跟踪一个属性,如按物种,您是正确的,字典将是最好的。如果您想要跟踪更多属性,请执行以下操作
def find_by_attribute(self, attribute_name, value):
return [a for a in self.animals if getattr(a, attribute_name) == value]以避免编写重复的代码。这应该有助于你开始工作
https://stackoverflow.com/questions/56152529
复制相似问题