我當時正在製作一個小動物看護程序,其中我首先創建了一個類名Critter。 我創建的第一個方法是構造函數方法,其中我做了三個名爲「名稱」,「飢餓」,「無聊」的變量。
我在這堂課創建了很多方法。編譯代碼時出現屬性錯誤
我無法弄清楚我做錯了什麼。
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'
在'increase'中,你正在訪問'hunger'和'boredom'作爲局部變量,而不是實例屬性。 – chepner