Global variables within classes.

Donn Ingle donn.ingle at gmail.com
Fri Nov 9 16:48:56 EST 2007


>> I thought this might be a case for multiple inheritance
> ???
Well, in terms of having Canvas and Thing inherit from Stack and thereby
(somehow, not sure how) they would both have access to Stack.stack (a list)
 
> 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...

No can do:
Canvas ---> Stack <--- Thing
Both Canvas and Thing have to use the same Stack. It gets things pushed onto
it by them both.

> 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.
Sorry, didn't want to write an overly long post.

a Canvas holds many Things (graphics) and it pushes each Thing onto the
Stack. The Things also push data onto the same Stack. After that the Stack
pops and draws each Thing to the screen.

What I'm asking about is subtle and I don't know how to word it: how can
Classes share common objects without using global variables specifically
named within them?


## == API in another module perhaps ===
Class Stack:
 def push(self,stuff):
  pass

Class Canvas:
 def do(self):
  s.push("data") #I don't feel right about 's' here.

Class Thing:
 def buzz(self):
  print s.pop(0)

## == User space code area ===
s = Stack() #I want to avoid this direct naming to 's'
c = Canvas()
c.push("bozo")
t = Thing()
t.buzz()

Hope that makes more sense.
\d





More information about the Python-list mailing list