I was making a critter caretaker program in which i first created a class names Critter.
The first method i created is the constructor method in which i made three variables named "name", "hunger", "boredom".
I created many methods in this class.
I am not able to figure out what i have done wrong.
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'
martineau
124k29 gold badges181 silver badges319 bronze badges
asked Nov 7, 2015 at 18:32
Sahib Navlani
801 silver badge12 bronze badges
1 Answer 1
You have at least two problems.
One is you need to use
class Critter(object):
not
def Critter(object):
The second is the
def init(self, name, hunger=0, boredom=0):
should be
def __init__(self, name, hunger=0, boredom=0):
answered Nov 7, 2015 at 18:44
martineau
124k29 gold badges181 silver badges319 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Sahib Navlani
Thanks a lot .I know that a did a nooby mistake,but thanks for answering
martineau
Sure — you're welcome. Your code was declaring a function that returned nothing (
None) and was being called instead of class __init__() method (which why you hadn't encountered the second error yet). BTW you misspelled Medi-Caps on your profile page.lang-py
hungerandboredomas local variables, not instance attributes, inincrease.