You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过用户输入获取Python Dog类的特定实例信息

如何通过名称获取动态创建的Dog类实例信息

我定义了Dog类,通过用户输入创建了多个该类的实例对象。现在需要获取某个特定Dog实例的信息,但尝试遍历实例时发现类本身不可迭代。我只会直接声明对象时的信息获取方式(例如d1 = Dog("Sam", 5, "Labrador")后,通过print(d1.name)获取属性),但当前场景下该方法不适用。假设用户需要获取名为Sam的狗的信息,该如何实现?

原代码如下:

# let's make a dog class
dog_list = ["labrador", "beagle", "poodle", "husky"]  # global variable


class Dog:
    obj_instances = []
    # attributes of the class

    def __init__(self, name, age, breed):
        self.name = name
        self.age = age
        self.breed = breed
        # add all instances to this list
        self.obj_instances.append(self.name)

    # string representation of the object
    def __str__(self):
        return f"{self.name}({self.age}) is a {self.breed}"

    # find dog's favorite toy
    def favorite_toy(self):
        favorite_toy = None
        # here we have a list of toys
        toy_list = ["ball", "squeaky bone", "frisbee", "pillow"]
        dog_counter = 0

        # go through each type of dog until we match the breed of our dog object
        # then we match the position of the breed to the position of the toy
        for dogType in dog_list:
            if self.breed == dogType:
                favorite_toy = toy_list[dog_counter]
                break
            else:
                favorite_toy = "unknown"
            dog_counter = dog_counter + 1

        return f"{self.name}'s favorite toy is {favorite_toy}."


# d1 = Dog("Millard", 6, "labrador")
# print(d1.name)
print("Let's add 3 dogs to our Dog class.")
dog_entry = 0
while dog_entry < 2:
    dog_name = input("What is your dog's name?\n")
    dog_age = input("What is your dog's age?\n")
    dog_breed = input("What is your dog's breed?\n").lower()
    Dog(dog_name, dog_age, dog_breed)
    dog_entry = dog_entry + 1

# Let's check the dogs we added
print(f"Current instances: {Dog.obj_instances}")
for x in Dog:
    print(x)
# Let's ask the user to tell us which dog they'd like to know more about
confirmation = input("Would you like to know more about one of these dogs? (y/n)\n").lower()
dog_observed = None
if confirmation[0] == "y":
    dog_observed = input("Which dog are you interested in knowing more about?\n")
    # Let's show them that dog's information
    count = 0
    for dogs in Dog.obj_instances:
        if Dog.obj_instances[count] == dog_observed:
            print("Found dog") # how to get that objects information without object !!!!!!!!!!!
            break
        count = count + 1
else:
    print("Thanks for coming. Have a good day.")

解决步骤

  1. 修复实例存储问题
    原代码中Dog.obj_instances只存储了狗的名字字符串,而非实例对象本身,这是无法获取实例属性的核心原因。修改__init__方法,将实例本身添加到列表中:
def __init__(self, name, age, breed):
    self.name = name
    self.age = age
    self.breed = breed
    # 存储实例对象而非名字
    self.obj_instances.append(self)
  1. 正确遍历实例
    类本身不可迭代,所以要遍历存储实例的Dog.obj_instances列表,替换原代码中for x in Dog:的错误代码:
# 遍历实例列表输出所有狗的信息
print("Current instances:")
for dog in Dog.obj_instances:
    print(dog)
  1. 根据名称查找并获取实例信息
    遍历Dog.obj_instances,匹配目标名称对应的实例,之后就能直接访问该实例的属性(如name、age)和方法(如favorite_toy()):
if confirmation[0] == "y":
    dog_observed = input("Which dog are you interested in knowing more about?\n")
    # 查找目标实例
    target_dog = None
    for dog in Dog.obj_instances:
        if dog.name == dog_observed:
            target_dog = dog
            break
    if target_dog:
        print(f"找到目标狗信息:")
        print(f"名字:{target_dog.name}")
        print(f"年龄:{target_dog.age}")
        print(f"品种:{target_dog.breed}")
        print(target_dog.favorite_toy())
    else:
        print(f"没有找到名为{dog_observed}的狗")
else:
    print("Thanks for coming. Have a good day.")

修改后的完整代码

dog_list = ["labrador", "beagle", "poodle", "husky"]  # 全局变量


class Dog:
    obj_instances = []

    def __init__(self, name, age, breed):
        self.name = name
        self.age = age
        self.breed = breed
        # 添加实例对象到列表
        self.obj_instances.append(self)

    def __str__(self):
        return f"{self.name}({self.age}) is a {self.breed}"

    def favorite_toy(self):
        favorite_toy = None
        toy_list = ["ball", "squeaky bone", "frisbee", "pillow"]
        dog_counter = 0

        for dogType in dog_list:
            if self.breed == dogType:
                favorite_toy = toy_list[dog_counter]
                break
            else:
                favorite_toy = "unknown"
            dog_counter += 1

        return f"{self.name}'s favorite toy is {favorite_toy}."


print("Let's add 2 dogs to our Dog class.")
dog_entry = 0
while dog_entry < 2:
    dog_name = input("What is your dog's name?\n")
    dog_age = input("What is your dog's age?\n")
    dog_breed = input("What is your dog's breed?\n").lower()
    Dog(dog_name, dog_age, dog_breed)
    dog_entry += 1

# 查看已添加的狗
print("Current instances:")
for dog in Dog.obj_instances:
    print(dog)

# 查询特定狗的信息
confirmation = input("Would you like to know more about one of these dogs? (y/n)\n").lower()
if confirmation[0] == "y":
    dog_observed = input("Which dog are you interested in knowing more about?\n")
    target_dog = None
    for dog in Dog.obj_instances:
        if dog.name == dog_observed:
            target_dog = dog
            break
    if target_dog:
        print(f"\n{target_dog.name}的详细信息:")
        print(f"年龄:{target_dog.age}")
        print(f"品种:{target_dog.breed}")
        print(target_dog.favorite_toy())
    else:
        print(f"未找到名为{dog_observed}的狗")
else:
    print("Thanks for coming. Have a good day.")

内容的提问来源于stack exchange,提问作者David Huerta Gudiño

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 22:10:42