【问题标题】:How to loop through a list of the instantiated objects in Python classes?如何遍历 Python 类中实例化对象的列表?
【发布时间】:2020-11-21 21:30:36
【问题描述】:

我需要创建一个实例化对象列表并循环遍历类的对象(Pet、Jumper、Dog、BigDog、SmallDog、Cat、HouseCat)。但是这些对象属于不同的类,有不同的方法。主要部分按预期打印结果,但我不知道将其更改为对象列表并循环遍历它们。请你帮助我好吗?谢谢。我的代码如下(类部分可以忽略,只关注主要部分):

class Pet:
"""
insert a class docstring
"""
# Create two variables kind and color; assign value
    kind = "animal"
    color = "brown"

    def __init__(self, name):
    """
    Constructor for Pet
    """
    # In the constructor, initialize the pets name
        self.name = name

    def __str__(self):
    """
    insert a method docstring
    """

    # Print the name and description of pet so that it matches the
    # sample output from assignment
        print("I am a " + Pet.color + " animal named " + self.name)
        print(self.kind + "\n" + self.color)

    def do_tricks(self):
    """
    insert a method docstring
    """

    # Print the name of the pet and that it is doing tricks
        print(self.name + " is doing tricks")

    # Call the speak method
    # self.speak()

    # Call the jump method
    # self.jump()

    def speak(self):  # this will be overridden - leave as is
        pass

    def jump(self):   # this will be overridden - leave as is
        pass


class Jumper(Pet):
"""
This is a mixin class for jump
"""

    def jump(self):
    """
    insert a method docstring
    """
    # Print pet's name and that the Pet is jumping
        print(self.name + " is jumping")


class Dog(Jumper):    
"""
insert a Class docstring
"""

# Change kind to canine
    kind = "canine"

    def __str__(self):
    """
    insert the method docstring
    """

    # Print the name and a description of dog so that it matches the
    # sample output from assignment
        print("I am a dog named " + self.name)
        print(self.kind + "\n" + self.color)

    def __call__(self):
    """
    insert a method docstring
    """

    # Rollover action prints the name of the dog and that it is rolling
    # over
        print(self.name + " is rolling over")
    # Owner action returns the name of the owner
        print("My owner is George")


class BigDog(Dog):    
"""
insert a Class docstring
"""

# Change the color to tan
    color = "tan"

    def __str__(self):
    """
    insert a method docstring
    """
    # Print the name and description of BigDog so that it matches the
    # sample output from assignment
        print(self.name + " is a large, muscular dog ")
        print(self.kind + "\n" + self.color)

    def speak(self):
    """
    insert a method docstring
    """

    # Print dogs name and what it says
        print(self.name + " says Woof!!!")


class SmallDog(Dog):    
"""
insert a Class docstring
"""

# Change the color to brindle
    color = "brindle"

    def __str__(self):
    """
    insert a method docstring
    """

    # Print the name and description of SmallDog so that it matches the
    # sample output from assignment
        print(self.name + " is a tiny, cute dog")
        print(self.kind + "\n" + self.color)

    def speak(self):
    """
    insert a method docstring
    """
    # Print dogs name and what it says
        print(self.name + " says Yip!")


class Cat(Jumper):     
"""
insert a Class docstring
"""

# Change the kind to feline
    kind = "feline"

    def __str__(self):
    """
    insert a method docstring
    """
    # Print the name and description of cat so that it matches the
    # sample output from assignment
        print("I am a cat named " + self.name)
        print(self.kind + "\n" + self.color)

    def speak(self):
    """
    insert a method docstring
    """
    # Print cats name and what it says
        print(self.name + " says Meow!!!")

    def climb(self):
    """
    insert a method docstring
    """
    # Print the name of the cat and that it is climbing
        print(self.name + " is climbing the curtains again")


class HouseCat(Cat):     
"""
insert a Class docstring
"""
# Change the color to white
    color = "white"

    def __str__(self):
    """
    insert a method docstring
    """
    # Print the name and description of the house cat so that it matches
    # the sample output from assignment
        print(self.name + " is a cat with fluffy, " + self.color + " fur")
        print(self.kind + "\n" + self.color)

    def speak(self):
    """
    insert a method docstring
    """
    # Print cats name and what it says
        print(self.name + " says Purr")enter code here

print(__name__)
if __name__ == "__main__":

    my_pet = Pet("Rover")
    my_pet.__str__()
    my_pet.do_tricks()
    print("-----------------------------------")

    my_cat = Cat("Lion")
    my_cat.__str__()
    my_cat.do_tricks()
    my_cat.speak()
    my_cat.jump()
    my_cat.climb()
    print("-----------------------------------")

    my_dog = Dog("Roo")
    my_dog.__str__()
    my_dog.do_tricks()
    my_dog.jump()
    my_dog.__call__()
    print("-----------------------------------")

    my_big_dog = BigDog("Noah")
    my_big_dog.__str__()
    my_big_dog.do_tricks()
    my_big_dog.speak()
    my_big_dog.jump()
    my_big_dog.__call__()
    print("-----------------------------------")

    my_small_dog = SmallDog("Lucky")
    my_small_dog.__str__()
    my_small_dog.do_tricks()
    my_small_dog.speak()
    my_small_dog.jump()
    my_small_dog.__call__()
    print("-----------------------------------")

    my_house_cat = HouseCat("Zebra")
    my_house_cat.__str__()
    my_house_cat.do_tricks()
    my_house_cat.speak()
    my_house_cat.jump()
    my_house_cat.climb()
    print("-----------------------------------")

【问题讨论】:

  • 如果我正确理解了您的问题,那么您只需将对象引用存储在列表中即可。
  • 与遍历任何列表的方式相同,作为用户定义类的实例的对象没有什么特别之处,everything 在 Python 中都是一个对象。所以你只需遍历你的列表,for item in my_list: ...
  • 我不明白你想做什么。首先向我展示您的尝试作为代码。

标签: python list loops class object


【解决方案1】:

也许您可以在每个类中创建一个附加方法,该方法共享相同的签名,但具有不同的实现。然后你可以在for 循环中调用它。

class Dog:
    # ...
    def perform(self):
        self.do_tricks()
        self.jump()

class HouseCat:
    # ...
    def perform(self):
        self.do_tricks()
        self.speak()
        self.jump()
        self.climb()

# ...

if __name__ == '__main__':
    animals = [   # make a list of animals
       Pet("Rover"),
       Cat("Lion"),
       # ...
    ]
    for animal in animals:  # call on a shared method on each animal
        animal.perform()

【讨论】:

  • 非常感谢,亲爱的埃德里克。这正是我想要的并按预期运行。很高兴学习这些新知识。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-30
  • 2021-11-21
  • 1970-01-01
  • 2016-05-15
  • 2016-12-29
  • 2021-11-25
  • 1970-01-01
相关资源
最近更新 更多