[Tutor] Class methods
Alan Gauld
alan.gauld at btinternet.com
Mon Jun 27 09:54:21 CEST 2011
"David Merrick" <merrickdav at gmail.com> wrote
> Is it possible too have
>
> crit1 = Critter("Dave")
> crit2 = Critter("Sweetie")
> farm = [crit1,crit2] #List#
>
> and then be able to use Critters methods on farm?
No, Marc has already answered that.
> class Critter(object):
>
> """A virtual pet"""
> def __init__(self, name, hunger = 0, boredom = 0):
>
> # __ denotes private method
> def __pass_time(self):
> self.hunger += 1
> self.boredom += 1
> self.__str__()
>
> def __str__(self):
> print("Hunger is",self.hunger, "Boredom is " ,self.boredom)
> print("Unhappines is ",self.hunger + self.boredom," and Mood
> is
> ",self.mood)
This is a really bad idea. Please do not do this,
it will almost certainly lead to problems later.
__str__ should return a string. It should not print anything.
Then you can simply call
print (self)
at the end of the pass_time method
or call
print (farm[0])
in your external code.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list