我正在制作一个小动物看守程序,我首先创建了一个类名Critter。
我创建的第一个方法是构造函数方法,其中我创建了三个名为“name”,“hunger”,“boredom”的变量。
我在这个课程中创建了很多方法。
我无法弄清楚我做错了什么。
def Critter(object):
def init(self,name,hunger = 0,boredom = 0):
self.name = name
self.hunger = hunger
self.boredom = boredom
def increase(self):
self.hunger += 2
self.boredom += 2
return hunger,boredom
def mood(self):
unhappiness = self.hunger + self.boredom
if 5 < unhappiness < 9:
mood1 = "unhappy."
elif 9 < unhappiness < 14:
mood1 = "Frustrated"
elif unhappiness > 14:
mood1 = "Mad"
return mood1
def talk(self):
print "Critter's name is ",self.name.upper()," and it is ",self.mood()," today."
def eat(self,food = 4):
self.hunger -= food
if self.hunger < 0:
self.hunger = 0
self.increase()
def play(self,play = 4):
self.boredom -= play
if self.boredom < 0:
self.boredom = 0
self.increase()
def main():
choice = None
name = raw_input("Please enter the name of the critter = ")
crit1 = Critter(name)
while choice != 0:
print """
0 - EXIT
1 - SEE YOUR CRITTER'S MOOD
2 - FEED YOUR CRITTER
3 - PLAY WITH YOUR CRITTER
"""
choice = int(raw_input("Enter your choice = "))
if choice == 1:
crit1.talk()
elif choice == 2:
crit1.eat()
elif choice == 3:
crit1.play()
if choice == 0:
print "Good bye ......"
main()
THIS IS THE CODE ,when i run it shows an error
Traceback (most recent call last):
File "C:\Users\sahib navlani\Desktop\gfh.py", line 65, in <module>
main()
File "C:\Users\sahib navlani\Desktop\gfh.py", line 54, in main
crit1.talk()
AttributeError: 'NoneType' object has no attribute 'talk'
答案 0 :(得分:2)
你至少有两个问题。
一个是你需要使用
class Critter(object):
不是
def Critter(object):
第二个是
def init(self, name, hunger=0, boredom=0):
应该是
def __init__(self, name, hunger=0, boredom=0):