473,387 Members | 1,493 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,387 software developers and data experts.

Basic Class/Instance Question

Ready to go insane here. Class A, taking on a default value for a
variable. Instantiating two separate objects of A() gives me a shared
val list object. Just see the example bellow:
class A(object):
def __init__(self, val=[]):
self.val=val

obj1 = A()
obj2 = A()

print obj1 is obj2 # False - as expected
print obj1.val is obj2.val # True! - Why... oh god WHY
-----------
Using python 2.4. Is this a bug with this version of python? How can I
trust the rest of the universe is still in place? Could she still like
me? Many questions I have. Lets start with the python problem for now.

Thanks,
Sia

May 23 '07 #1
5 1076
Il 23 May 2007 04:07:19 -0700, Siah ha scritto:
Ready to go insane here. Class A, taking on a default value for a
__init__ is a function, taking a default value of [], which is a list,
which is a mutable object. That said, you should remember that this means
that such default value is 'shared' between all instances. If you don't
want that, do something like:

def __init__(self, defaultvalue=None):
if defaultvalue is None:
defaultvalue=[]

http://docs.python.org/tut/node6.htm...00000000000000
--
Alan Franzoni <al***************@gmail.com>
-
Togli .xyz dalla mia email per contattarmi.
Remove .xyz from my address in order to contact me.
-
GPG Key Fingerprint (Key ID = FE068F3E):
5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E
May 23 '07 #2
Siah a écrit :
Ready to go insane here. Class A, taking on a default value for a
variable. Instantiating two separate objects of A() gives me a shared
val list object. Just see the example bellow:
class A(object):
def __init__(self, val=[]):
self.val=val

obj1 = A()
obj2 = A()

print obj1 is obj2 # False - as expected
print obj1.val is obj2.val # True! - Why... oh god WHY
-----------
Using python 2.4. Is this a bug with this version of python? How can I
trust the rest of the universe is still in place? Could she still like
me? Many questions I have. Lets start with the python problem for now.
This is a FAQ. Default arguments are only evaled once - when the def
statement is evaled (which is usually at import time). The solution is
simple: don't use mutable objects as default arguments:

class A(object):
def __init__(self, val=None):
if val is None:
val = []
self.val=val

FWIW, do you really believe such a 'bug' would have stayed unnoticed ?-)

Else, the rest of the universe seems to be in place, and I don't know if
she'll still like you if she learn you didn't read the FAQ before
posting !-)

HTH
May 23 '07 #3
On 2007-05-23, Bruno Desthuilliers <br********************@wtf.websiteburo.oops.comwr ote:
Siah a écrit :
>Ready to go insane here. Class A, taking on a default value for a
variable. Instantiating two separate objects of A() gives me a shared
val list object. Just see the example bellow:
class A(object):
def __init__(self, val=[]):
self.val=val

obj1 = A()
obj2 = A()

print obj1 is obj2 # False - as expected
print obj1.val is obj2.val # True! - Why... oh god WHY


-----------
Using python 2.4. Is this a bug with this version of python? How can I
trust the rest of the universe is still in place? Could she still like
me? Many questions I have. Lets start with the python problem for now.

This is a FAQ. Default arguments are only evaled once - when the def
statement is evaled (which is usually at import time). The solution is
simple: don't use mutable objects as default arguments:
An immutable object would have given the same behaviour in this case

class A(object):
def __init__(self, val = ()):
self.val=val

obj1 = A()
obj2 = A()

print obj1 is obj2 # False
print obj1.val is obj2.val # True

May 23 '07 #4
Antoon Pardon wrote:
>This is a FAQ. Default arguments are only evaled once - when the def
statement is evaled (which is usually at import time). The solution is
simple: don't use mutable objects as default arguments:

An immutable object would have given the same behaviour in this case

class A(object):
def __init__(self, val = ()):
self.val=val

obj1 = A()
obj2 = A()

print obj1 is obj2 # False
print obj1.val is obj2.val # True

Yeah, but is that a problem? Since you can not change them anyway,
there's no harm.
W

May 23 '07 #5
On 2007-05-23, Wildemar Wildenburger <wi******@freakmail.dewrote:
Antoon Pardon wrote:
>>This is a FAQ. Default arguments are only evaled once - when the def
statement is evaled (which is usually at import time). The solution is
simple: don't use mutable objects as default arguments:

An immutable object would have given the same behaviour in this case

class A(object):
def __init__(self, val = ()):
self.val=val

obj1 = A()
obj2 = A()

print obj1 is obj2 # False
print obj1.val is obj2.val # True

Yeah, but is that a problem? Since you can not change them anyway,
there's no harm.
I think it can make comprehension harder if you suggest in your
explanation that a partcilular behaviour is linked to an object
being mutable while that has nothing to do with it.

You are correct that one can't mutate the val attribute but
some code might depend on the distinction identical or not
instead of equal or not. Not understanding this issue of
default arguments could cause a bug in such code even
if the default argument is not mutable.

--
Antoon Pardon
May 24 '07 #6

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

Similar topics

4
by: Richard Spooner | last post by:
Hey, I'm very new to python and am trying to do the following. I may get the jargon wrong at times but hopefully you can see what I'm trying to do... I have created a threaded class which...
4
by: Jason Shohet | last post by:
I noticed that there are two ways I declare classes: 1. public class xxxx { } 2. Somewierdclass myClass; The 2nd example exists provided I have a 'using' statement at the top that...
12
by: Learning C# | last post by:
I hope this is an ok place to post real beginner stuff. Basically I need to know the difference between a field, and a static field. My book sux and doesn't explain this well. It seems that a...
5
by: Paul Bromley | last post by:
I have written a similar enquiry to this newsgroup, but had no responses - hence I will rephrase it with the hope that someone will answer. I am new to using Classes, but trying hard to get the...
6
by: pinorama123 | last post by:
I have an ASP.NET application that contains a few classes that I have built. One of my objects is a user object. I have a pretty basic question about how this would work. If I have multiple...
7
by: jason | last post by:
In the microsoft starter kit Time Tracker application, the data access layer code consist of three cs files. DataAccessHelper.cs DataAcess.cs SQLDataAccessLayer.cs DataAcccessHelper appears...
2
by: Jimmy | last post by:
This is a basic question. Does Page related member variable values only be set in the Page they are executed? Example code like below public partial class _Default : System.Web.UI.Page { string...
14
by: MartinRinehart | last post by:
Working on parser for my language, I see that all classes (Token, Production, Statement, ...) have one thing in common. They all maintain start and stop positions in the source text. So it seems...
9
by: Peskov Dmitry | last post by:
It is a very basic question.Surely i got something wrong in my basic understanding. //Contents of file1.cpp using namespace std; #include <iostream> template <typename T> class my_stack;
3
by: Scott Stark | last post by:
Hello, I'm trying to get a better handle on OOP programming principles in VB.NET. Forgive me if this question is sort of basic, but here's what I want to do. I have a collection of Employee...
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:
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
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.