【发布时间】:2019-05-16 18:38:58
【问题描述】:
当我尝试使用 a 的属性时(请参阅下面的代码),我收到一条错误消息,指出该对象没有属性,例如名称。 hasattr('a','name') 输出错误。例如,我希望能够在方法 display_info 中使用属性名称,但似乎我的对象没有任何给定的属性。同时 find_by_attribute 方法工作正常并输出具有给定属性的对象,我在这里感到困惑。也许我以错误的方式创建我的对象?
尝试使用 say_hi 方法时会出现同样的错误。
@dataclass
class Animal:
name: str
species: str
gender: str
age: int
mood: str
@classmethod
def say_hi(self):
print(f'{self.name} the {self.species} says hi!')
def display_info(self):
print('Name:',self.name)
print('Species:',self.species)
print('Gender:',self.gender)
print('Age: %d' % self.age)
print('Mood:',self.mood)
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? ')
gender = input('What gender is it? ')
age = int(input('What age is it? '))
mood = input('How is the animal feeling? ')
a = Animal(name, species, gender, age, mood)
self.animals.append(a)
def find_by_attribute(self, attribute_name, value):
return [a for a in self.animals if getattr(a, attribute_name) == value]
a = Zoo()
a.add_animal()
【问题讨论】:
-
hasattr('a','name')和hasattr(a,'name')不一样。对我来说似乎是一个错字。 -
无论哪种方式都返回 false :(
-
@Hoog,因为它是data class
-
你在这里传递什么
a:Zoo或Animal? -
say_hi不应该是类方法;摆脱装饰器。
标签: python python-3.x