访问列表中对象的属性

时间:2016-03-16 17:22:45

标签: python

我正在使用一本名为 Python for Absolute Beginners 的书,并且正在本书的第8章(软件对象)中进行挑战。我的代码有效,但我想为代码添加另一个功能;我需要添加什么代码才能与特定生物一起添加/播放/交谈?

在我的代码选择#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.")

2 个答案:

答案 0 :(得分:2)

在为特定生物喂食的分支中,您有一行noc.eat() - noc是一个列表,没有eat()方法。您需要访问输入指定的生物,并在该对象上调用eat()方法。类似的东西:

for c in noc:
    if c.name == sctd:
        c.eat()
        break

(虽然这个例子有一个问题,如果多个生物匹配sctd - 解决这个问题,我将留给你)

您的代码的另一个小问题反馈:文档字符串应该是定义中的第一个语句PEP 0257

答案 1 :(得分:0)

只是一个小小的注释,我认为类似import random的约定应该放在开头而不是放在类中,这也解决了@nthall引起的问题,即你的docstring当前不是第一个对象。