Instantiation of 2nd object appends 1st?
Steve Holden
sholden at holdenweb.com
Wed Nov 8 08:11:47 EST 2000
Carl Bray wrote:
>
> In the following code A is instantiated with a list. A assigns the list to
> the attribute A_list.
>
> My problem is that when I create a second instance of A the values in the
> second are those of the 1st AND 2nd instantiations rather than just the 2nd!
>
> Why is this??
>
> THE OUTPUT
>
> [[1, 2, 3]]
> [[1, 2, 3], [1, 2, 3]]
>
> THE CODE
>
> class A:
>
> A_list = []
>
This makes A_list an attribute of the class rather than each instance,
since the declaration is in the class scope rather than that of a method...
> def __init__(self, the_list):
>
> # Append the list to A's list
> self.A_list.append(the_list)
>
Here you pick up the class attribute, even though you are qualifying the
instance with A_list. And why appeand here if you don't want to build
an increasing list? You could just assign a copy ... as in:
def __init__(self, the_list):
self.A_list = the_list[:]
That way, each instance gets its own attribute. You should remove the
class attribute assignment, since this forces the name to be shared across
all instances.
> def __repr__(self):
> return repr(self.A_list)
>
> for x in range(2):
>
> print A([1,2,3])
>
> VERSION
>
> Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
> Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
HTH
regards
Steve
--
Helping people meet their information needs with training and technology.
703 967 0887 sholden at bellatlantic.net http://www.holdenweb.com/
More information about the Python-list
mailing list