我正在使用一本名为 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.")
请您参考如下方法:
在喂养特定动物的分支中,您有 noc.eat() 行——noc 是一个列表,其中没有 eat( ) 方法。您需要访问输入指定的小动物,并对该对象调用 eat() 方法。像这样的东西:
for c in noc:
if c.name == sctd:
c.eat()
break
(尽管如果多个小动物匹配 sctd 则此示例存在问题——我会留给您解决这个问题)
关于您的代码的另一个小反馈点:根据 PEP 0257,文档字符串应该是定义中的第一条语句.
