Skip to main content
 首页 » 编程设计

python之内置.AttributeError : 'Pet' object has no attribute 'get_name'

2024年11月01日13飞鱼

我目前收到此错误:

builtins.AttributeError: 'Pet' object has no attribute 'get_name'

它在程序末尾的 for 循环之后显示代码行 print(item.get_name())。

这是我的类(class):

class Pet: 
 
    def __init__(self, name, type, age): 
        self.__name = name 
        self.__type = type 
        self.__age = age 
 
        def set_name(self, name): 
            self.__name = name 
 
        def set_type(self, type): 
            self.__type = type 
 
        def set_age(self, age): 
            self.__age = age 
 
        def get_name(self): 
            return self.__name 
 
        def get_type(self): 
            return self.__type 
 
        def get_age(self): 
            return self.__age 

这是我的程序:

import pet 
 
def main(): 
 
    animals = make_list() 
 
    print('Here is the data you entered:') 
    display_list(animals) 
 
def make_list(): 
 
    animal_list = [] 
 
    print('Enter data for 3 animals.') 
    for count in range(1,4): 
        print('Pet number '+str(count) + ':') 
        name = input('Enter the name: ') 
        type = input('Enter the type: ') 
        age = input('Enter the age: ') 
        print() 
 
        animal = pet.Pet(name, type, age) 
 
        animal_list.append(animal) 
 
    return animal_list 
 
def display_list(animal_list): 
 
    for item in animal_list: 
        print(item.get_name()) 
        print(item.get_type()) 
        print(item.get_age()) 
        print() 
 
main() 

请您参考如下方法:

Pet 的所有方法都需要以相同的缩进级别开始。您需要取消缩进从 set_name 到 get_age 的每一行。