[Tutor] Class methods

Alan Gauld alan.gauld at btinternet.com
Wed Jun 22 09:58:03 CEST 2011


"David Merrick" <merrickdav at gmail.com> wrote 

> class Critter(object):
> 
>    def __init__(self, name, hunger = 0, boredom = 0):
>    def __pass_time(self):
>    def __str__(self):
>    @property
>    def mood(self):
>    def talk(self):
>    def eat(self):
>    def play(self):
> 
> class Farm(Critter):

I still don't think a Farm is a type of Critter...

>    def __init__(self,farmlet):
>       Critter.__init__(self,farmlet)

This will set the name to farmlet, which I don't 
think you want.

>    def talk(self,farmlet):

You don't need to pass farmlet in since the 
class has farmlet stored inside it. 
You can access farmlet with self.farmlet.

>        for critter in farmlet:
>            print("Hello")
>            Critter.talk(farmlet)

You want the instance to talk not the class.
So you need to use critter.talk() And the talk 
method does not take any arguments except 
self. What you are doing here is calling the 
class method with an instance value of farmlet.
ie self in that method gets the value of farmlet.

> def main():
>    crit1 = Critter("Sweetie")
>    crit2 = Critter("Dave")
>    farmlet = [crit1,crit2]
>    f = Farm(farmlet)
> 
>    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 = input("Choice: ")
>        print()
> 
>        # exit
>        if choice == "0":
>            print("Good-bye.")
> 
>        # listen to your critter
>        elif choice == "1":
>            f.talk(farmlet)
> 
>        # feed your critter
>        elif choice == "2":
>            f.eat(farmlet)

Note that f.eat is a method you inherit from Critter.
The Critter method does not take any arguments 
so this will fail.

>        # play with your critter
>        elif choice == "3":
>            f.play(farmlet)

Same with f.play()

> Traceback (most recent call last):
>  File "D:/David/Python/programs/critter_farm3.py", line 72, in talk
>    Critter.talk(farmlet)
>  File "D:/David/Python/programs/critter_farm3.py", line 38, in talk
>    print("I'm", self.name, "and I feel", self.mood, "now.\n")
> AttributeError: 'list' object has no attribute 'name'

This is because you are accessing the method via 
the class and passing farmlet as the instance value
rather than sending the message to the innstance 
directly. Use

critter.talk()   # and no farmlet needed! 

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list