Help with classes

Kaden sfam at
Sat Dec 1 23:16:37 EST 2001


I discovered Python a while back, but have just now had the time to
actually look at it.  I have experience with UNIX shell scripting and I
know enough C/C++ to get a vague idea what the code is doing by reading
it, although I can't write it to save my life.  So I'm not a _complete_
idiot when it comes to programming, but I'm pretty close.

So, with that here's the problem I'm having:

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):
        print "You put the", element, "in your basket."

    def remove(self,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.  That's where
the 'state = ""' lines came in.  I thought I'd set a variable and then
have it checked.  I don't know how to do this though. I played with a
couple things, but couldn't get anything to work, so I just removed the
things I tried and left the variables since they really aren't affecting
anything at this point.

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?

I'm not asking for anyone to do my homework for me or anything like that.
If you have a URL that explains this that you could offer me that would
be fine.  I don't have a problem figuring things out on my own.  I just
don't know where to look to get the information I need to be able to do


More information about the Python-list mailing list