[Python-bugs-list] append add to list in both father and inherit class (PR#105)

guido@CNRI.Reston.VA.US guido@CNRI.Reston.VA.US
Wed, 13 Oct 1999 14:22:32 -0400 (EDT)


> Full_Name: Igal Harel
> Version: 1.5.2
> OS: solaris 7
> Submission from: (NULL) (212.29.248.198)
> 
> 
> ## List's Append BUG Example 
> 
> class A:
>     FList = []
>     def Append(self,Item=''):
> 	self.FList.append(Item)
> 
> class B(A):
>     ""
> 
> class C(A):
>     FB = None
>     def __init__(self):
> 	self.FB = B()
> 
> c = C()
> c.Append('Item for container ( instance of C ) only')
> print c.FB.FList,c.FList

You're not very clear about what happens or what you had expected, but
my guess is that you're confused by Python's rules about sharing
objects.

There is only a single FList object shared by all instances of class
A, including instances of its subclasses (B and C).  This object can
be accessed as self.FList but that is really just another name for
A.FList.  When you append to it, the change will be reflected no
matter which name you use to access it later.

If you want each A instance to have its own FList object, use a
constructor method:

class A:
    def __init__(self):
        self.FList = []
    def Append(self, Item=''):
        ....as before....

--Guido van Rossum (home page: http://www.python.org/~guido/)