473,466 Members | 1,457 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Problem when subclass instance changes base class instance variable

Hi All!

I have noticed a strange behavior when using a constant identifier to
initialize an instance list variable in a base class and then trying to
modifying the list in subclasses by using either the list.extend method or
even by having the subclass create a whole new list in the variable.

The following example illustrates the situation.

Lbase = ['Initial Base Data']

LSub1 = ['SubClass 1 data']

LSub2 = ['SubClass 2 data']

##

class BaseClass:

def __init__(self):

self.data = Lbase #<---- this fails??

# self.data = ['Initial Base Data'] #<---- this works

def printData(self):

print self.data

##

class SubClass1(BaseClass):

def __init__(self):

BaseClass.__init__(self)

self.data.extend(LSub1)

# self.data += LSub1

##

class SubClass2(BaseClass):

def __init__(self):

BaseClass.__init__(self)

self.data.extend(LSub2)

# self.data += LSub2

s1 = SubClass1()

s1.printData()

s2 = SubClass2()

s2.printData()

s11 = SubClass1()

s11.printData()

s21 = SubClass2()

s21.printData()

s1.printData()

['Initial Base Data', 'SubClass 1 data']

['Initial Base Data', 'SubClass 1 data', 'SubClass 2 data']

['Initial Base Data', 'SubClass 1 data', 'SubClass 2 data', 'SubClass 1
data']

['Initial Base Data', 'SubClass 1 data', 'SubClass 2 data', 'SubClass 1
data', 'SubClass 2 data']

['Initial Base Data', 'SubClass 1 data', 'SubClass 2 data', 'SubClass 1
data', 'SubClass 2 data']


It looks like the instance variable is acting like a class variable with all
the subclass changes accumulating as more objects are created.

Does anyone have an explanation for this behavior?

Are other mutable sequence types affected the same way?

To fix the problem you simply use a literal list to initialize the variable
in the base class instead of an identifier.

This problem does not exist if the data variable is a string, maybe because
it is immutable?

I am using Python Ver 2.3.

Does this code behave the same way in 2.4,


Jul 19 '05 #1
1 2403
Gerry Sutton wrote:
I have noticed a strange behavior when using a constant identifier to
initialize an instance list variable in a base class and then trying to
modifying the list in subclasses by using either the list.extend method or
even by having the subclass create a whole new list in the variable.

The following example illustrates the situation. Lbase = ['Initial Base Data'] class BaseClass:
def __init__(self):
self.data*=*Lbase*****************#<----**this*fails??


self.data and Lbase are now bound to the same variable. Consequently changes
to that variable through self.data affect Lbase and vice versa. This is
standard Python behaviour. If you want to use Lbase as a kind of initial
value, modify BaseClass to make a (shallow) copy:

class BaseClass:
def __init__(self):
self.data = list(Lbase)

Now every BaseClass instance gets its separate copy. If you have nested
mutables, e. g. a list of lists, look into the copy module for deepcopy().

Peter

Jul 19 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Angelos Karantzalis | last post by:
Hi guys. I've come across a problem when I tried to serialize a class into xml, only to discover that the parent class's XML Serialization properties weren't included in the output xml. ...
3
by: john | last post by:
I have a situation where i have a base class and a sub-class. A null instance of the sub-class is passed into a function. The function needs to create a new instance of the sub-class, but the...
2
by: Andrew G. J. Fung | last post by:
Can anyone please explain to me why the code below throws an exception? It seems to occur when deserializing an instance of a subclass, whose base class holds a struct, where said struct holds an...
8
by: Lou Pecora | last post by:
I've been scanning Python in a Nutshell, but this seems to be either undoable or so subtle that I don't know how to do it. I want to subclass a base class that is returned from a Standard Library...
31
by: damacy | last post by:
hi, there. i have a problem writing a program which can obtain ip addresses of machines running in the same local network. say, there are 4 machines present in the network; , , and and if i...
3
by: sernamar | last post by:
Hi, I have the following base class class UnitOfMeasure { public: //... std::string& GetName() {return _uomName;}; //... protected:
11
by: eBob.com | last post by:
I have this nasty problem with Shared methods and what I think of as "global storage" - i.e. storage declared outside of any subroutines or functions. In the simple example below this "global"...
18
by: Eric | last post by:
Ok...this seems to be treading into some really esoteric areas of c++. I will do my best to explain this issue, but I don't fully understand what is happening myself. I am hoping that the problem...
13
by: Rafe | last post by:
Hi, I am in a situation where I feel I am being forced to abandon a clean module structure in favor of a large single module. If anyone can save my sanity here I would be forever grateful. My...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.