correlation between seemingly independent instances of same class

N

nikipore

Hello,

the results of the following code boggle me. i would have expected
that y.data is not affected by setting z.data.

Regards Jan


--code---------------------------------------------
class Test:
def __init__(self, x={}):
self.data = x
#end def
#end class Test

y = Test()
z = Test()

print 'y.data = ',y.data
print 'z.data = ',z.data

z.data['B'] = 2 # this statement also sets y.data
z.data= {'A': 1} # this statement doesn't

print 'y.data = ',y.data
print 'z.data = ',z.data
--code end-------------------------------------------

--output-----------------------------------------------
"C:\Program Files\Python25\pythonw" -u "thestrangething.py"
y.data = {}
z.data = {}
y.data = {'B': 2}
z.data = {'A': 1}
 
D

Dennis Lee Bieber

I guess it /has/ been about two weeks since this bit the last
person...

def __init__(self, x={}):

def __init__(self, x=None):
if x:
self.data = x
else:
self.data = {}

Python Reference Manual, section 7.5, Function Definitions
"""
....
Default parameter values are evaluated when the function definition is
executed. This means that the expression is evaluated once, when the
function is defined, and that that same ``pre-computed'' value is used
for each call. This is especially important to understand when a default
parameter is a mutable object, such as a list or a dictionary: if the
function modifies the object (e.g. by appending an item to a list), the
default value is in effect modified. This is generally not what was
intended. A way around this is to use None as the default, and
explicitly test for it in the body of the function, e.g.:
....
"""
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top