Global variables within classes.

Donn Ingle donn.ingle at
Sat Nov 10 15:01:01 CET 2007

Very interesting reply. I must ask a few questions, interleaved:

> 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:
What's the difference between "same Stack" and "same instance of Stack"? I
thought I knew what an instance was, but this code has made me doubt my

> class Stack:
>     list = []
Okay, this has me a little weirded-out. How is this different from putting
it in: 
def __init__(self):
        self.list = []
I see from tests that it is different, but I don't quite grok it. Who owns
the list ref?

>     def pop(self):
>         item = self.list[-1]
>         del self.list[-1]
>         return item
Is there some reason you do all that and not a self.list.pop(0)?
> class Canvas:
>     def __init__(self):
>         self.s = Stack()
Surely this makes a unique instance within Canvas such that it's a new

> class Thing:
>     def __init__(self):
>         self.s = Stack()
Same question again -- my brain is telling me this is *another* Stack and
not the same one that it's in Canvas at all.

It looks like it could work for me, but I gotta get it in my head first :)

> 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:
> c = Canvas()
> c.push("bozo")
> t = Thing(c.getStack())   #associate t with c
This one I understand better because it does not imply anything - it's
easier to follow and it's where my head is at with Python, but your first
example is a whole new world.

Thanks for the post!

More information about the Python-list mailing list