Why the result

H

HYRY

Why the third print stement output "'comments': [(1, 2, 3)]", I think
it should be [].
I am using
Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)]
on win32.

# program
class PicInfo:
def __init__(self, intro="", tags="", comments=[]):
self.picintro = intro
self.pictags = tags
self.comments = comments

def addcomment(self, comment):
self.comments.insert(0, comment)

dbdata = PicInfo()
print dbdata.__dict__
dbdata.addcomment((1,2,3))
print dbdata.__dict__
dbdata = PicInfo()
print dbdata.__dict__

# output
{'pictags': '', 'comments': [], 'picintro': ''}
{'pictags': '', 'comments': [(1, 2, 3)], 'picintro': ''}
{'pictags': '', 'comments': [(1, 2, 3)], 'picintro': ''} <- why
comments is not []?
 
B

Bruno Desthuilliers

HYRY said:
Why the third print stement output "'comments': [(1, 2, 3)]", I think
it should be [].
I am using
Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)]
on win32.

# program
class PicInfo:
def __init__(self, intro="", tags="", comments=[]):

This is a FAQ - and one of the most (in)famous Python's gotchas. Default
arguments are eval'd *only once* - when the def statement is eval'd,
which is usually at import time. So using a mutable object as default
value makes this object behaving somehow like a C 'static' local
variable, ie it keeps it value from call to call.

The canonical idiom is to use None instead:

class PicInfo(object):
def __init__(self, intro="", tags="", comments=None):
self.picintro = intro
self.pictags = tags
if comments is None:
comments = []
self.comments = comments
 

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

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,077
Latest member
SangMoor21

Latest Threads

Top