Python中访问类对象属性遇异常?列表存对象后属性访问问题求助
问题:无法正确访问Animal对象的属性,输出方法内存地址
我尝试将Animal对象存入Animals类的animalList列表,但调用show方法时无法正确获取age和name属性,输出的是方法的内存地址。
原代码
class Animal: def __init__(self, age, name) -> None: self.age = age self.name = name def getAge(self): return self.age def getName(self): return self.name class Animals: def __init__(self, index) -> None: self.index = index self.animalList = None def startInsert(self): newTable = list() for i in range(self.index): newTable.append(None) self.animalList = newTable def insertInIndex(self, index, animalObject): for i in range(len(self.animalList)): if i == index: self.animalList[i] = animalObject def show(this): for i in range(len(this.animalList)): if this.animalList[i] is not None: print('index: ',i,', Age: ',this.animalList[i].getAge,', Name: ',this.animalList[i].getAge) animals = Animals(5) animals.startInsert() cow = Animal(2, "Cow") dog = Animal(3, "Dog") animals.insertInIndex(2, cow) animals.insertInIndex(3, dog) animals.show()
期望输出
index: 2, Age: 2, Type: Cow index: 3, Age: 3, Type: Dog
实际输出
index: 2 , Age: <bound method Animal.getAge of <__main__.Animal object at 0x00000200ead03cd0>> , Type: <bound method Animal.getAge of <__main__.Animal object at 0x00000200ead03cd0>> index: 3 , Age: <bound method Animal.getAge of <__main__.Animal object at 0x00000200ead03c70>> , Type: <bound method Animal.getAge of <__main__.Animal object at 0x00000200ead03c70>>
错误原因与修复方法
- 方法未调用:
getAge和getName是实例方法,必须加括号()才能执行并返回属性值,直接写方法名会返回方法对象的内存地址。 - 字段调用错误:原show方法中两次调用了
getAge,第二个应该改为getName(),同时输出文本要和期望一致,把Name改成Type。 - 可选优化:
insertInIndex方法无需循环遍历,直接通过索引赋值即可;startInsert可以用列表生成式简化代码。
修正后的完整代码
class Animal: def __init__(self, age, name) -> None: self.age = age self.name = name def getAge(self): return self.age def getName(self): return self.name class Animals: def __init__(self, index) -> None: self.index = index self.animalList = None def startInsert(self): # 用列表生成式简化初始化 self.animalList = [None] * self.index def insertInIndex(self, index, animalObject): # 直接通过索引赋值,无需循环 if 0 <= index < len(self.animalList): self.animalList[index] = animalObject def show(this): for i in range(len(this.animalList)): animal = this.animalList[i] if animal is not None: # 调用方法并修正输出文本 print(f'index: {i}, Age: {animal.getAge()}, Type: {animal.getName()}') animals = Animals(5) animals.startInsert() cow = Animal(2, "Cow") dog = Animal(3, "Dog") animals.insertInIndex(2, cow) animals.insertInIndex(3, dog) animals.show()
运行修正后的代码,输出结果与期望一致:
index: 2, Age: 2, Type: Cow index: 3, Age: 3, Type: Dog
内容的提问来源于stack exchange,提问作者asker
相关产品推荐
相关产品推荐

