81 lines
2.0 KiB
Plaintext
81 lines
2.0 KiB
Plaintext
From: florent.heyworth at radbit.com (Florent Heyworth)
|
|
Date: Sun, 11 Apr 1999 12:57:58 +0200
|
|
Subject: Python's object model
|
|
References: <37102ED0.933EDDA6@usa.net>
|
|
Message-ID: <37108036.3F33C237@radbit.com>
|
|
Content-Length: 1719
|
|
X-UID: 423
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|