Global variables within classes.
uestc_mahui at 163.com
uestc_mahui at 163.com
Sat Nov 10 04:31:43 EST 2007
On 11 10 , 5 48 , Donn Ingle <donn.in... at gmail.com> wrote:
> ## == 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
If you mean that all instances of Class Canvas and Thing will share
the *same* Stack, I think we can do it kind of like this:
## == API in another module perhaps ===
class Stack:
list = []
def push(self, item):
self.list.append(item)
def pop(self):
item = self.list[-1]
del self.list[-1]
return item
class Canvas:
def __init__(self):
self.s = Stack()
def push(self, item):
self.s.push(item)
class Thing:
def __init__(self):
self.s = Stack()
def buzz(self):
print self.s.pop()
## == User space code area ===
c = Canvas()
c.push("bozo")
t = Thing()
t.buzz()
or: if you want a pair of instances of class Canvas and class Thing
share
the *same* instance of class Stack, maybe we can make it like this:
## == API in another module perhaps ===
class Stack:
def __init__(self):
self.list = []
def push(self, item):
self.list.append(item)
def pop(self):
item = self.list[-1]
del self.list[-1]
return item
class Canvas:
def __init__(self, stack = Stack()):
self.s = stack
def push(self, item):
self.s.push(item)
def getStack(self):
return self.s
class Thing:
def __init__(self, stack = Stack()):
self.s = stack
def buzz(self):
print self.s.pop()
def getStack(self):
return self.s
## == User space code area ===
c = Canvas()
c.push("bozo")
t = Thing(c.getStack()) #associate t with c
t.buzz()
More information about the Python-list
mailing list