【问题标题】:Object does not contain the attributes given对象不包含给定的属性
【发布时间】: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
  • 你在这里传递什么aZooAnimal
  • say_hi 不应该是类方法;摆脱装饰器。

标签: python python-3.x


【解决方案1】:

好吧,最后一行的aadd_animal 方法中的a 不同:

  • 第一个是Zoo 的实例,它没有任何名为name 的属性,但它有一个动物列表,其中每个动物都有分配的属性..
  • 第二个a 可能让你感到困惑,这是方法内部的一个局部变量,添加到Zoo 实例的animals 列表中。

因此,如果您想访问 name 属性,您需要在实例 a 内的 animals 列表的元素上调用它,如下所示:

a = Zoo()
a.add_animal()                       # answer the inputs ...
print(hasattr(a.animals[0], 'name')  # => True

我建议不要在类/方法的外部和内部使用相同的变量名,以消除任何混淆。

希望对你有帮助

编辑(在评论中回答问题:例如,我将如何修改 display_info 以返回给定动物的动物属性?)

您不需要方法display_info,因为Animaldataclass,您可以打印它:

# continuation for code from before

for animal in a.animals:
    print(animal)

输出类似:

Animal(name='tiger', species='cat', gender='male', age=12, mood='hungry')

如果您想将信息存储在字符串中以备后用,您可以:

animal_info = str(a.animals[0])

如果您想打印特定的动物,只说 12 岁的,您可以:

print([animal for animal in a.animals if animal.age == 12])

这将根据需要显示动物列表。

【讨论】:

  • 好的,谢谢你的帮助。那么我将如何修改display_info 以返回给定动物的动物属性?我觉得使用数据类让这对我来说变得更加困难..
猜你喜欢
  • 1970-01-01
  • 2013-02-13
  • 2013-10-29
  • 2013-05-13
  • 1970-01-01
  • 2014-03-03
  • 1970-01-01
  • 1970-01-01
  • 2017-05-16
相关资源
最近更新 更多