473,379 Members | 1,373 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,379 software developers and data experts.

Unexpected behavior when initializing class

Hello everybody,

I've banged my ahead around for a while trying to figure out why
multiple instances of a class share the same instance variable. I've
stripped down my code to the following, which reproduces my problem.

class Test(object):
def __init__(self, v=[]):
self.values = v

def addValue(self, v):
self.values += [v]
return

a = Test()
a.addValue(1)
print a.values # Should print [1]
b = Test()
print b.values # Should print empty list
b.addValue(2)
print a.values # Should print [1]

The output I get is:

[1]
[1]
[1, 2]

The output I am expecting is:

[1]
[]
[1]

Another strange thing is that if I initialize with a different value,
the new instance will not share the 'values' attribute with the other
two:

c = Test([9])
print c.values # Prints [9] as it should
print a.values # Still prints [1, 2]

There is something I clearly don't understand here. Can anybody
explain? Thanks!

Python 2.4.4 (#1, Oct 23 2006, 13:58:18)
[GCC 4.1.1 20061011 (Red Hat 4.1.1-30)] on linux2

Alfred J. Fazio,
af****@smoothstone.com
Nov 28 '07 #1
7 1087
"al**********@gmail.com" <al**********@gmail.comwrites:
Hello everybody,

I've banged my ahead around for a while trying to figure out why
multiple instances of a class share the same instance variable. I've
stripped down my code to the following, which reproduces my problem.

class Test(object):
def __init__(self, v=[]):
self.values = v
You have to understand that the default value for v - an empty list -
is made at compile time - and it's the *same* list every time it's
used i.e. if you don't pass in a value for v when you make new
instances of your class.

A common paradigm to get round this - assuming you want a different
empty list each time - is something like:

def __init__(self, v = None):
self.values = v if v else []

(or maybe test explicitly for None, but you get the idea.)
Nov 28 '07 #2
On Nov 28, 3:31 am, Paul Rudin <paul.nos...@rudin.co.ukwrote:
You have to understand that the default value for v - an empty list -
is made at compile time - and it's the *same* list every time it's
used i.e. if you don't pass in a value for v when you make new
instances of your class.
*smack*!! That's me smacking myself on the forehead. I now remember
reading a long time ago that this was an FAQ! Thanks for the reply,
Paul. :)

Alfred J. Fazio,
al**********@gmail.com
Nov 28 '07 #3
al**********@gmail.com wrote:
Hello everybody,

I've banged my ahead around for a while trying to figure out why
multiple instances of a class share the same instance variable. I've
stripped down my code to the following, which reproduces my problem.
This is a *feature* of Python that bytes *ever* newbie at least once. ;-)

See
http://www.python.org/doc/faq/genera...etween-objects
class Test(object):
def __init__(self, v=[]):
self.values = v

def addValue(self, v):
self.values += [v]
return

a = Test()
a.addValue(1)
print a.values # Should print [1]
b = Test()
print b.values # Should print empty list
b.addValue(2)
print a.values # Should print [1]

The output I get is:

[1]
[1]
[1, 2]

The output I am expecting is:

[1]
[]
[1]

Another strange thing is that if I initialize with a different value,
the new instance will not share the 'values' attribute with the other
two:

c = Test([9])
print c.values # Prints [9] as it should
print a.values # Still prints [1, 2]

There is something I clearly don't understand here. Can anybody
explain? Thanks!

Python 2.4.4 (#1, Oct 23 2006, 13:58:18)
[GCC 4.1.1 20061011 (Red Hat 4.1.1-30)] on linux2

Alfred J. Fazio,
af****@smoothstone.com
Nov 28 '07 #4
On Nov 28, 7:19 pm, "alfred.fa...@gmail.com" <alfred.fa...@gmail.com>
wrote:
Hello everybody,

I've banged my ahead around for a while trying to figure out why
multiple instances of a class share the same instance variable. I've
stripped down my code to the following, which reproduces my problem.

class Test(object):
def __init__(self, v=[]):
self.values = v

def addValue(self, v):
self.values += [v]
return

a = Test()
a.addValue(1)
print a.values # Should print [1]
b = Test()
print b.values # Should print empty list
b.addValue(2)
print a.values # Should print [1]

The output I get is:

[1]
[1]
[1, 2]

The output I am expecting is:

[1]
[]
[1]

Another strange thing is that if I initialize with a different value,
the new instance will not share the 'values' attribute with the other
two:

c = Test([9])
print c.values # Prints [9] as it should
print a.values # Still prints [1, 2]

There is something I clearly don't understand here. Can anybody
explain? Thanks!
http://www.python.org/doc/faq/genera...etween-objects

http://docs.python.org/tut/node6.htm...00000000000000
Nov 28 '07 #5
Paul Rudin <pa*********@rudin.co.ukwrote:
You have to understand that the default value for v - an empty list -
is made at compile time
Not at compile time: the default value is created at runtime when the def
statement is executed.

Nov 28 '07 #6
Mel
Paul Rudin wrote:
"al**********@gmail.com" <al**********@gmail.comwrites:
A common paradigm to get round this - assuming you want a different
empty list each time - is something like:

def __init__(self, v = None):
self.values = v if v else []

(or maybe test explicitly for None, but you get the idea.)
Do test explicitly for None. Otherwise, if you do

a = []
x = ThatClass (a)
it will so happen that x.values will be an empty list, but it won't be
the same list as a.

Mel.
Nov 28 '07 #7
On Nov 28, 3:04 pm, Mel <mwil...@the-wire.comwrote:
Paul Rudin wrote:
"alfred.fa...@gmail.com" <alfred.fa...@gmail.comwrites:
A common paradigm to get round this - assuming you want a different
empty list each time - is something like:
def __init__(self, v = None):
self.values = v if v else []
(or maybe test explicitly for None, but you get the idea.)

Do test explicitly for None. Otherwise, if you do

a = []
x = ThatClass (a)

it will so happen that x.values will be an empty list, but it won't be
the same list as a.

Mel.
Yes. Another much safer possibility is to make a copy of the initial
v:

def __init__(self, values=[]):
self.values = list(values)

As a nice side effect, the object can be initialised with any
iterable.

--
Arnaud

Nov 28 '07 #8

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

Similar topics

9
by: Xiangliang Meng | last post by:
The fragment code: #include <iostream> using namespace std; class Integer { int i; public: Integer() : i(0) {};
2
by: Attila Feher | last post by:
Hi all, I have not done much work around exceptions; and even when I do I avoid exception specifications. But now I have to teach people about these language facilities, so I am trying them out...
16
by: He Shiming | last post by:
Hi, I'm having a little bit of trouble regarding pointer casting in my program. I don't understand why the following two cases produce different results. Case 1: IInterface *pInterface = new...
4
by: Generic Usenet Account | last post by:
I am seeing some unexpected behavior while using the STL "includes" algorithm. I am not sure if this is a bug with the template header files in our STL distribution, or if this is how it should...
6
by: Samuel M. Smith | last post by:
I have been playing around with a subclass of dict wrt a recipe for setting dict items using attribute syntax. The dict class has some read only attributes that generate an exception if I try to...
4
by: duffdevice | last post by:
Hi, I came across this unexpected behavior while working on something else. I am attempting to return a custom type by value from a global function. I have a trace in the custom class's copy...
11
by: hogtiedtoawaterbuffalo | last post by:
I have a template class that works fine when I implement it with <int>, but when I use <floator <doubleit doesn't work. The class has a dynamic array of type T that gets instantiated in my...
2
by: Dimitri Furman | last post by:
SQL Server 2000 SP4. Running the script below prints 'Unexpected': ----------------------------- DECLARE @String AS varchar(1) SELECT @String = 'z' IF @String LIKE ''
5
by: anne.nospam01 | last post by:
Dear fellow Pythonians, I just stumbled upon the following unexpected behavior: class TestType(type): def Foo(self): return 'TestType Foo' class Test(object): __metaclass__ = TestType def...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

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.