unexpected class behaviour

J

Jan Schäfer

Hi all,

can anyone explain the behaviour of the following code sniplet:

---> schnipp <---
class Base(object):
def __init__( self, lst=[] ):
self.varlist = lst

def addVar( self, var ):
self.varlist.append(var)

class Derived(Base):
def __init__( self, var ):
Base.__init__(self)
self.addVar(var)

vars = ['foo', 'bar']

for ivar in vars:
obj = Derived(ivar)
print ivar, obj, obj.varlist
---> schnapp <---

After running (Python 2.5.1), I get the following output:
foo <__main__.Derived object at 0xb7c608cc> ['foo']
bar <__main__.Derived object at 0xb7c6092c> ['foo', 'bar']

So, I get two different objects, but how does the 'foo' get into the second
varlist? I'm a little bit confused about this, any ideas?

Thanks in advance

Jan
 
K

kaer

well, it *is* explained in the tutorial, the language reference, and the
FAQ, so yes, it can be explained ;-)

for more information, see this page:

http://effbot.org/zone/default-values.htm

</F>

Well, you may want replace the last line by:
print ivar, obj, obj.varlist, id(obj.varlist)

To have another behavior, you may want replace the 3 first lines by:
class Base(object):
def __init__( self, lst=None ):
if lst is None: lst=[]
self.varlist = lst

Enjoy Python !
 

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,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top