在Python中从类调用列表

zphenhs4  于 2022-11-19  发布在  Python
关注(0)|答案(1)|浏览(153)

如果我从一个类中调用一个列表,输出的不是列表的内容。
我想调用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))
vlju58qv

vlju58qv1#

这是因为你把宠物对象存储在一个列表中,所以它会打印出对象。你应该覆盖字符串函数来解决这个问题,如下所示:

class Pet:
    def __init__(self, name, owner):
        self.name = name
        self.owner = owner

    def __str__(self):
        return self.name

名字类应该是这样的:

class Name:
    def __init__(self, first, last):
        self.first = first
        self.last = last

    def __str__(self):
        return self.first + " " + self.last

而get pets函数应该是这样的:

def get_pets_string(an_owner):
    res = str(an_owner.name.first) + " " + str(an_owner.name.last) + "'s pets are: "
    for pet in an_owner.pets:
        res += str(pet) + ", "
    return res

这是如果你想保持它就像你已经创建了它,但是有更容易的方法来编写这个代码,如:

class Owner:
    def __init__(self, name: str):
        self.name = name
        self.pets = []

    def add_pet(self, pet: str):
        self.pets.append(pet)

    def get_pets(self):
        res = self.name + "'s pets are: "
        for pet in self.pets:
            res += pet + ", "
        return res

o = Owner("David Friend")
o.add_pet("Boggle Joyner")
o.add_pet("Artemis Joyner")
print(o.get_pets())

相关问题