Python 访问列表中对象的属性

Python 访问列表中对象的属性,python,Python,我正在使用一本名为《Python》的书,这本书的第8章(软件对象)中有一个挑战。我的代码可以工作,但我想为代码添加另一个功能;我需要添加什么代码来喂养/玩耍/与特定动物交谈 在我代码的choice#7(7-喂养特定的动物)中,我已经编写了一些代码,但不起作用。如何访问/更改用户选择的特定对象的属性 此外,是否有改进/缩短代码的反馈 # Critter Caretaker # A virtual pet to care for class Critter(object): import r

我正在使用一本名为《Python》的书,这本书的第8章(软件对象)中有一个挑战。我的代码可以工作,但我想为代码添加另一个功能;我需要添加什么代码来喂养/玩耍/与特定动物交谈

在我代码的choice#7(7-喂养特定的动物)中,我已经编写了一些代码,但不起作用。如何访问/更改用户选择的特定对象的属性

此外,是否有改进/缩短代码的反馈

# Critter Caretaker
# A virtual pet to care for
class Critter(object):
    import random
    """A virtual pet"""
    def __init__(self, name, hunger = random.randint(0,9), boredom = random.randint(0,11)):
        self.name = name
        self.hunger = hunger
        self.boredom = boredom

    def __pass_time(self):
        self.hunger +=1
        self.boredom +=1

    def __str__(self):

        m = "name is: {}, hunger is: {}, boredom is: {}".format(self.name, self.hunger,self.boredom)


        return m

    @property
    def mood(self):
        unhappiness = self.hunger + self.boredom
        if unhappiness <5:
            m = "happy"
        elif 5 <= unhappiness <=10:
            m = "okay"
        elif 11 <= unhappiness <=15:
            m = "frustrated"
        else:
            m= "mad"
        return m

    def talk(self):
        print("I'm", self.name, "and I feel", self.mood, "now.\n")
        self.__pass_time()

    def eat(self, food=3):
        print("Yummy! Thank you.")
        self.hunger -=food
        if self.hunger <0:
            self.hunger = 0
        self.__pass_time()

    def play(self, fun=4):

        print("That was fun! Thanks")
        self.boredom -=fun
        if self.boredom <0:
            self.boredom = 0
        self.__pass_time()

def main():
    noc = []
    noc.append(Critter("Chicken"))
    print("An critter named Chicken has been created")
    choice = None
    while choice != "0":
        print \
        ("""
        Critter Caretaker

        0 - Quit
        1 - Listen to all your critters
        2 - Feed all your critters
        3 - Play with all your critters
        4 - Create a new critter
        5 - Show a list of critters
        6 - Delete a critter
        7 - Feed a specific critter
        """)

        choice = input("Choice: ")
        print()

        # exit
        if choice == "0":
            print("Good-bye.")

        # listen to critters
        elif choice == "1":
            if len(noc) != 0:
                i.talk()
            else:
                print("No critters exist")
        # feed your critters
        elif choice == "2":
            if len(noc) != 0: 
                for i in noc:
                    print(i.name, "says:", end = " ")
                    i.eat()
        # play with your critters
        elif choice == "3":
            if len(noc) != 0: 
                for i in noc:
                    print(i.name, "says:", end = " ")
                    i.play()
            else:
                print("No critter exists")
        # Create a new critter
        elif choice == "4":
            noc.append(Critter(input("Enter a name for your new critter: ")))
        # Show critters
        elif choice =="5":
            b = 0
            if len(noc) != 0: 
                for i in noc:
                    b +=1
                    print(b, "." ,i.name)
            else:
                print("No critter exists")
        # delete a critter
        elif choice == "6":
            a = int(input("Enter the serial number of critter you want to delete: "))
            a = a -1
            del noc[a]

        # feed a specific critter
        elif choice == "7":
            sctd = input("Enter name of critter you want to feed: ")
            if sctd in noc:
                noc.eat()
            else:
                print("That critter doesn't exists")


        # print attributes of critters
        elif choice == "919":
            for i in noc:
                print(i)
        else:
            print("\nSorry, but", choice, "isn't valid.")

main()
("\n\nPress the enter key to exit.")
#动物管理员
#要照顾的虚拟宠物
类生物(对象):
随机输入
“虚拟宠物”
定义初始化(self,name,饥饿=random.randint(0,9),无聊=random.randint(0,11)):
self.name=名称
饥饿
无聊
定义通过时间(自身):
自我饥饿+=1
自我厌倦+=1
定义(自我):
m=“name是:{},饥饿是:{},无聊是:{}”。格式(self.name,self.饥饿,self.boredom)
返回m
@财产
情绪(自我):
不快乐=自我饥饿+自我厌倦

如果喂食特定生物的分支中存在不快乐,则行
noc.eat()
--
noc
是一个列表,其中没有
eat()
方法。您需要访问输入指定的生物,并对该对象调用
eat()
方法。比如:

for c in noc:
    if c.name == sctd:
        c.eat()
        break
(尽管这个例子有一个问题,如果多个生物匹配
sctd
——解决这个问题我将留给你)


关于代码的另一个次要反馈:docstring应该是定义中的第一条语句。

只是一个小提示,我认为类似于
import random
的约定可能应该放在开始处,而不是放在类中,这样也可以解决@nthall提出的问题也就是说,您的docstring当前不是第一个对象。

这并不能回答这个问题。一旦你有足够的钱,你将能够;相反或者你想问?我不是在问一个问题,我只是有点含糊其辞,因为我对python规范在这个问题上只有90%的把握。