对象不包含给定的属性

2024-05-03 12:18:07 发布

您现在位置:Python中文网/ 问答频道 /正文

当我试图使用的属性(见下面的代码),我得到一个错误,说对象没有属性,例如名称。hasattr('a','name')输出false。例如,我希望能够在display\u info方法中使用属性名,但似乎我的对象没有任何给定的属性。同时,方法find\ by\ attribute运行良好,并输出具有给定属性的对象,我在这里感到困惑。也许我用错误的方式创建了我的对象?你知道吗

当尝试使用say\u 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()

Tags: 对象nameselfinputage属性isdef
1条回答
网友
1楼 · 发布于 2024-05-03 12:18:07

最后一行的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\u info以返回给定动物的动物属性?)

您不需要方法display_info,因为Animal是一个dataclass您可以打印它:

# 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])

这将显示所需的动物列表。你知道吗

相关问题 更多 >