我有以下代碼:
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()
我想將一個物件發送Animal到我的串列animalList中,該物件是Animals該類的一部分
我的問題是我無法從我的班級訪問我的班級的Age和Name屬性AnimalAnimals
我的預期輸出是:
index: 2, Age: 2, Type: Cow
index: 3, Age: 3, Type: Dog
我所做的是:
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)
但我的控制臺只顯示下一個記憶體地址:
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>>
謝謝。
uj5u.com熱心網友回復:
問題出在這一行:
print('index: ',i,', Age: ',this.animalList[i].getAge,', Name: ',this.animalList[i].getAge)
您正在列印this.animalList[i].getAge,這是一個功能。要實際獲取年齡,您必須呼叫函式,如this.animalList[i].getAge().
僅此一項就可以解決問題,但是,您的問題還有其他一些(次要)問題。在下面的代碼中,我洗掉了您的 getter 函式(這些函式是不必要的并且會導致您感到困惑),更正了縮進,并重構了一些代碼以使其看起來更好。我還洗掉了該animals.startInsert方法,因為它應該是建構式的一部分。我希望這可以幫助您更好地理解:
class Animal:
def __init__(self, age, name) -> None:
self.age = age
self.name = name
class Animals:
def __init__(self, index) -> None:
self.index = index
self.animalList = [None for i in range(index)]
def insertInIndex(self, index, animalObject):
self.animalList[index] = animalObject
def show(self):
for i in range(len(self.animalList)):
if self.animalList[i] is not None:
print('index: ', i, ', Age: ', self.animalList[i].age,
', Name: ', self.animalList[i].age)
animals = Animals(5)
cow = Animal(2, "Cow")
dog = Animal(3, "Dog")
animals.insertInIndex(2, cow)
animals.insertInIndex(3, dog)
animals.show()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/524587.html
