我開始學習 Python 中的 OOP。我有一個像這樣的簡單問題。例如,我有一個名為 Cat 的類,以及一個名為 ListOfCat 的類,其中包含一個 Cat 串列。現在我想列印貓名單。下面是我的代碼:
class Cat:
def __init__(self,name,color):
self.name = name
self.color = color
def __repr__(self):
return '{} {}'.format(self.name,self.color)
class ListOfCat:
list_of_cat=[]
def add_cat(self,cat):
self.list_of_cat.append(cat)
def __repr__(self):
pass #Need something here
Cat1 = Cat('Lulu','red')
Cat2 = Cat('Lala','white')
List1 = ListOfCat()
List1.add_cat(Cat1)
List1.add_cat(Cat2)
print(List1) #TypeError: __str__ returned non-string (type NoneType)
#Expected output: ['Lulu red','Lala white']
for cat in List1.list_of_cat: #I found this method on the internet but the result isn't what I want
print(cat)
#Lulu red
#Lala white
如果有人能告訴我在該pass行中輸入什么內容,我將不勝感激。
uj5u.com熱心網友回復:
有很多方法可以做到這一點。這是一個:
class Cat:
def __init__(self, name, colour):
self.name = name
self.colour = colour
def __repr__(self):
return f"'{self.name} {self.colour}'"
class ListOfCats:
def __init__(self):
self.loc = []
def addcat(self, cat):
self.loc.append(cat)
def __repr__(self):
return str(self.loc)
LOC = ListOfCats()
LOC.addcat(Cat('Lulu', 'red'))
LOC.addcat(Cat('Lala', 'white'))
print(LOC)
輸出:
['Lulu red', 'Lala white']
uj5u.com熱心網友回復:
我認為上面的答案回答了你的問題。但我想補充一點,你也可以輸入print(List1.list_of_cat)也可以。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/436652.html
上一篇:串列理解與自我參考的組合
