Global variables within classes.

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Fri Nov 9 17:43:16 EST 2007


Donn Ingle a écrit :
>>>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

Sorry but you're exemple is using classes, not instances. So while *you* 
may know what you mean, it's not decidable for me.

> Both Canvas and Thing have to use the same Stack.

You mean: both Canvas class and Thing class have to use the same Stack 
Class ? Or : for all Canvas instances and all Thing instances, there 
must be only one same Stack instance ? Or: a given (Canvas instance, 
Thing instance) couple must share a same Stack instance ? Or (etc...)

> It gets things pushed onto
> it by them both.

Both what ? classes ? instances ?-)

> 
>>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.

There's certainly a balance between being overly vague and being overly 
long !-)

> 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

I guess you mean "instances", not "classes".

> share common objects without using global variables specifically
> named within them?

Err...Perhaps a dumb question, but what about passing the "common 
objects" to initializers ?

> ## == 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()

# API land
class Stack(object):
    # ok, we all know what a stack is

class Canvas(object):
   def __init__(self, stack):
     self.stack = stack
   def do(self):
     self.stack.push("data")

class Thing(object):
   def __init__(self, stack):
     self.stack = stack
   def buzz(self):
     print self.stack.pop(0)


# Userland
s = Stack()
c = Canvas(s)
t = Thing(s)

c.do()
t.buzz()

HTH



More information about the Python-list mailing list