Global variables within classes.

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Fri Nov 9 14:23:27 EST 2007


Donn Ingle a écrit :
> Hi,
> I'm getting myself really confused. I have three classes. Two of them need
> to reference the third, like so:
> 
> Canvas ---> Stack <--- Thing
> 
> I am doing this right now:
> 
> s = Stack()
> 
> And then within <class Canvas:> I am referring directly to the global
> variable 's' (and again from Thing).
>
> Now, this works, but it bugs me somewhat.

Indeed...

> I don't want to limit a user to
> having to declare a global variable of a particular name.
> They should be able to say <Zombie = Stack()>
> 
> This may also leads to more confusion because the user can also make Things
> directly <mything = Thing()> and I want the new things to all reference the
> *same* Stack. (Right now it works because I reference 's' within Thing.)

> I thought this might be a case for multiple inheritance

???

> but I just keep
> getting recursion errors as one thing refers to another in a big mess.
> 
> Does that makes sense?

wrt/ all Thing instances having to refer to a same Stack instance, 
there's a pretty obvious answer: make the Stack instance an attribute of 
class Thing, ie:

class Thing(object):
   stack = Stack()

   def some_method(self, val):
      self.stack.push(val)
   # etc...

This way you can access this stack from the Thing class directly, as 
well as from any instance, subclass and subclass instance of.

Now the point that isn't clear is the exact relationship between Stack 
and Canvas. You didn't give enough details for any answer, advice or 
hint to make sens.

HTH



More information about the Python-list mailing list