gpt4 book ai didi

Python 回溯和名称错误

转载 作者:行者123 更新时间:2023-11-30 23:39:44 26 4
gpt4 key购买 nike

我对编程很陌生。我一直在尝试通过一本名为“绝对初学者的Python编程”的书来学习Python。我正在上课。我从书中的一个练习中复制了一些代码,并获得了 Traceback (most最近的调用最后): 和 NameError 消息。以下是我收到的错误消息和代码。请帮忙。谢谢!

Traceback (most recent call last):
File "C:\Python27\Ch8 Critter Caretaker Prg.py", line 5, in <module>
class Critter(object):
File "C:\Python27\Ch8 Critter Caretaker Prg.py", line 25, in Critter
mood = property(__get_mood)
NameError: name '_Critter__get_mood' is not defined
# Critter Caretaker
# A virtual pet to care for

class Critter(object):
"""A virtual pet"""
def __init__(self, name, hunger = 0, boredom = 0):
self.name = name
self.hunger = hunger
self.boredom = boredom
def __pass_time(self):
self.hunger += 1
self.bordedom += 1
def __get_mode(self):
unhappiness = self.hunger + self.boredom
if unhappiness < 5:
mood = "happy"
elif 5 <= unhappiness <= 10:
mood = "okay"
elif 11 <= unhappiness <= 15:
mood = "frustrated"
else:
mood = "mad"

mood = property(__get_mood)

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

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

def play(self, fun = 4):
print "Wheee!"
self.boredom -= fun
if self.boredom < 0:
self.boredom = 0
self.__pass_time()

def main():
crit_name = raw_input("What do you want to name your critter?: ")
crit = Critter(crit_name)

choice = None
while choice != "0":
print \
"""
Critter Caretaker

0 - Quit
1 - Listen to your critter
2 - Feed your critter
3 - Play with your critter
"""

choice = raw_input("Choice: ")
print

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

# listen to your critter
elif choice == "1":
crit.talk()

# feed your critter
elif choice == "2":
crit.eat()

# play with your critter
elif choice == "3":
crit.play()

# some unknown choie
else:
print "\nSorry, but", choice, "isn't a vaild choice."

main()
("\n\nPress the enter key to exit.")

最佳答案

正如已经提到的,您在 modemood 之间犯了一个拼写错误。但是,稍后您会遇到更多问题 - 您的 __get_mood 函数永远不会真正获得心情,因为它永远不会返回。另外,您可以使用 property 作为装饰器:

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

关于Python 回溯和名称错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13335541/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com