Python object instance inheriting changes to parent class by another instance

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • PyNoob123
    New Member
    • Jul 2010
    • 1

    Python object instance inheriting changes to parent class by another instance

    I am confused by this behaviour of Python(2.6.5), can someone shed light on why this happens?

    Code:
    class A(): 
        mylist=[]  
     
     
    class B(A):
        j=0
        def addToList(self):
            self.mylist.append(1)
         
    
    b1 = B()
    print len(b1.mylist)  # prints 0 , as A.mylist is empty
    b1.addToList()
    print len(b1.mylist)  # prints 1 , as we have added to A.mylist via addToList()
    
    b2 = B()
    print len(b2.mylist)  # prints 1 , not 0 !!! Why ?????
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    The list is initialized one time when class A is defined. When instance method addToList() is called and no attribute named muylist exists in the local scope, the interpreter finds mylist in the scope of A and appends 1 to it. If you want a new list created every time you create an instance, implement an __init__() function.

    Example:
    Code:
    class A:
        def __init__(self):
            self.mylist = []
    
    class B(A):
        def __init__(self):
            A.__init__(self)
        
        def addToList(self):
            print self
            print self.__dict__
            self.mylist.append(1)
    Some interaction:
    Code:
    >>> b1 = B()
    >>> b1.mylist
    []
    >>> b1.addToList()
    <__main__.B instance at 0x00F6E030>
    {'mylist': []}
    >>> b1.mylist
    [1]
    >>> b2 = B()
    >>> b2.addToList()
    <__main__.B instance at 0x00F6E6E8>
    {'mylist': []}
    >>> b2.mylist
    [1]
    >>>

    Comment

    • MojaveKid
      New Member
      • Sep 2007
      • 9

      #3
      mylist is a class variable and this is shared by all A (instance or not)

      Comment

      Working...