Help with classes
Hans Nowak
wurmy at earthlink.net
Sun Dec 2 01:21:24 EST 2001
Kaden wrote:
> I am playing with classes and trying to get the hang of them. I pretty
> much understand how inheritance and sub/superclassing goes I think. I
> just am having trouble figuring out how to get different classes to
> communicate with each other. The best way I can think to explain this is
> to post an example, so here's a nearly verbatum snippet from a tutorial I
> recently read:
>
> class Basket:
>
> def __init__(self,contents=None):
> self.contents = contents or []
>
> def add(self,element):
> self.contents.append(element)
> print "You put the", element, "in your basket."
>
> def remove(self,element):
> self.contents.remove(element)
> print "You remove the", element, "from your basket."
>
> def print_me(self):
> result = ""
> for element in self.contents:
> result = result + " " + `element`
> print "You look in your basket and see:" + result
>
> class NiceBasket(Basket):
>
> def open(self):
> print "You open your basket."
> state = "open"
>
> def close(self):
> print "You close your basket."
> state = "closed"
>
> Now then, the above class works. However, I want to be able to add some
> checks, such as checking to see if NiceBasket is closed when you try to
> add soemthing to it. I can't figure out how to do this.
By overloading methods. For example, add a new 'add' method to
NiceBasket, that checks, and if the check is successful, it calls
its parents' add method:
def add(self, element):
if self.state == "open":
Basket.add(self, element)
else:
print "The basket is not open."
I see that in your open and close methods, you use 'state' as a local
variable. This won't work; to make it visible throughout the instance
of NiceBasket, you should add "self." to it:
def close(self):
print "You close your basket."
self.state = "closed"
Initializing this state variable is probably a good idea too. To
do so, override the __init__ constructor in NiceBasket:
def __init__(self, contents=None):
Basket.__init__(self, contents)
self.state = "closed" # or open, depending on what you want
> The only way I could see this working is if the checks were done in the
> Basket class, but that would be the wrong place since NiceBasket is the
> class gives the baskets the ability to be opened. So any checks would
> have to be in NiceBasket, right?
Indeed, and the code samples above show you how. :-) Note that, when
you call a method in the same class, you do it like this:
self.method(args)
but calling a parent's method is done like this:
<parentclass>.method(self, args)
e.g. Basket.add(self, element).
HTH,
--Hans
More information about the Python-list
mailing list