【问题标题】:How to modify multiple objects in the same OOP class?如何修改同一个 OOP 类中的多个对象?
【发布时间】:2014-03-07 16:36:09
【问题描述】:

我根据教科书创建了一个程序,用于处理动物或Critters()。 目前它只处理一个小动物。

现在的问题是教科书要求我创建多个小动物,而不是函数对单个小动物起作用,而函数应该对所有小动物起作用。

我对如何做到这一点一无所知。

那么,如何将参数传递给多个小动物?

这是我的尝试(code sn-p):

Traceback (most recent call last):
  File "C:\pcrit.py", line 76, in main
    animal.eat(units)
AttributeError: 'str' object has no attribute 'eat'

^错误^

import random

class Critter(object):
    """A virtual pet."""
    def __init__(self,name):
        self.name = name
        self.boredom = random.randrange(0,30)
        self.hunger = random.randrange(0,30)
        print "A new critter is born:", self.name, "\n"

    def eat(self, food):
        food = int(food)
        self.hunger -= food
        if self.hunger < 0:
            self.hunger = 0

# main

critters = ["donkey","monkey","dog","horse"]
# make each animal into the Critter() class
for animal in critters:
    animal = Critter(animal)

units = (raw_input("How many play units? "))
for animal in critters:
    animal.eat(units)

【问题讨论】:

    标签: python class oop python-2.7


    【解决方案1】:

    你正在迭代

    critters = ["donkey","monkey","dog","horse"]
    

    那些是字符串,它们没有像eat 这样的方法。

    相反,您需要列出Critters

    critters = [Critter(name) for name in ["donkey", "monkey", "dog", "horse"]]
    

    你在做什么:

    for animal in critters:
        animal = Critter(animal)
    

    不将新对象分配回列表critters

    【讨论】:

    • 我不明白为什么遍历列表不起作用。如果我输入 donkey.eat(units),它可以手动工作
    • @user2071506 是的,但是您没有将 Critter 实例放回列表中,因此您总是遍历字符串。
    • @JonClements 没有你我会在哪里!
    • @jonrsharpe 之前有人在 Python 聊天中说过 :)... 我的回答保持不变 - “你会很平静”:p
    • @jonrsharpe 哦,我想我明白了......所以你的意思是 For 循环实际上是这样做的:"donkey".eat(units)?我不完全理解您答案中的代码,因此我正在尝试更多地在脑海中解决它以获得更简单的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    相关资源
    最近更新 更多