访问lis中对象的属性

2024-05-28 21:04:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为初学者使用一本名为Python的书,并在书的第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.")

Tags: to代码nameselfforifdefprint
2条回答

只需注意一点,我认为像import random这样的约定应该放在类的开头,而不是放在类的内部,这也解决了@nthall提出的问题,即docstring当前不是第一个对象。你知道吗

在喂养特定生物的分支中,行noc.eat()noc是一个列表,没有eat()方法。您需要访问由输入指定的critter,并对该对象调用eat()方法。比如:

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

(尽管这个例子有一个问题,如果有多个生物匹配sctd,那我就留给你解决)

关于代码的另一个次要反馈:docstring应该是定义中的第一条语句,如PEP 0257。你知道吗

相关问题 更多 >

    热门问题