如果我从一个类中调用一个列表,输出的不是列表的内容。
我想调用self.pets从类Owner,但输出的不是list的内容,而是that:
第一个
代码如下:
class Name:
def __init__(self, first, last):
self.first = first
self.last = last
class Pet:
def __init__(self, name, owner):
self.name = name
self.owner = owner
class Owner:
def __init__(self, name):
self.name = name
self.pets = []
def get_pets_string(an_owner):
return str(an_owner.name.first) + " " + str(an_owner.name.last) + "'s pets are: " + str(an_owner.pets)
owner_1 = Owner(Name("David", "Friend"))
owner_2 = Owner(Name("Audrey", "Hepburn"))
pet_1 = Pet(Name("Boggle", "Joyner"), owner_1)
pet_2 = Pet(Name("Artemis", "Joyner"), owner_1)
pet_3 = Pet(Name("Pippin", "Hepburn"), owner_2)
owner_1.pets.append(pet_1)
owner_1.pets.append(pet_2)
owner_2.pets.append(pet_3)
print(owner_2.name.first)
print(get_pets_string(owner_1))
print(get_pets_string(owner_2))
1条答案
按热度按时间vlju58qv1#
这是因为你把宠物对象存储在一个列表中,所以它会打印出对象。你应该覆盖字符串函数来解决这个问题,如下所示:
名字类应该是这样的:
而get pets函数应该是这样的:
这是如果你想保持它就像你已经创建了它,但是有更容易的方法来编写这个代码,如: