Python's object model
Florent Heyworth
florent.heyworth at radbit.com
Sun Apr 11 06:57:58 EDT 1999
Francois Bedard wrote:
> Hello,
>
> I'm new at Python. In the following program, "stack_1 pops stack_2's
> content" (that's actually what it prints), which is obviously not what
> I'm after - nor would expect. Is this how Python's object model really
> works (kindly explain), is there some arcane rule that I've missed, or
> is there some obvious mistake I just can't see?
>
> Aside from a few such quirks, it's quite an interesting language (I'm
> using 1.5.1 - on both Linux and NT).
>
> Thanks,
>
> Francois
>
> -------------------------------------
>
> class Stack:
> stack = []
>
> def push(self, value):
> self.stack.append(value)
>
> def pop(self):
> result = self.stack[-1]
> del self.stack[-1]
> return result
>
> class System:
> stack_1 = Stack()
> stack_2 = Stack()
>
> def __init__(self):
> self.stack_1.push('stack_1\'s content')
> self.stack_2.push('stack_2\'s content')
> print 'stack_1 pops', self.stack_1.pop()
>
> # 'main'
>
> system = System()
Hi Francois
what you're seeing is the difference between a class and an
instance variable. To see the behaviour you want you need to
modify your stack class as follows:
class Stack:
def __init__(self):
self.stack = []
def push(self, value):
self.stack.append(value)
def pop(self):
result = self.stack[-1]
del self.stack[-1]
return result
Otherwise the stack is a class variable which can be referred as
Stack.stack() (this would then act as a class global).
Cheers
Florent Heyworth
More information about the Python-list
mailing list