On March 17, 2008, Duncan Webb wrote:
> Here is a bit of code:
>
> class A:
>     def __init__(self, l=[]):
>         self.l = l
>
> class B:
>     def __init__(self):
>         self.l = []
>
> a1 = A()
> a2 = A()
>
> b1 = B()
> b2 = B()
>
> a1.l += ['a1']
> a2.l += ['a2']
> b1.l += ['b1']
> b2.l += ['b2']
>
> print 'a1:', a1.__dict__, '0x%08x' % abs(id(a1.l))
> print 'a2:', a2.__dict__, '0x%08x' % abs(id(a2.l))
> print 'b1:', b1.__dict__, '0x%08x' % abs(id(b1.l))
> print 'b2:', b2.__dict__, '0x%08x' % abs(id(b2.l))
>
> That gives:
> a1: {'l': ['a1', 'a2']} 0x484db114
> a2: {'l': ['a1', 'a2']} 0x484db114
> b1: {'l': ['b1']} 0x484db174
> b2: {'l': ['b2']} 0x484db2d4
>
> This behaviour seems a bit strange, clearly list is class A is the same
> objects for both instances and I'm wondering if this is correct?

Default arguments are evaluated when a function or method is defined, not when 
the associated code is called.

A somewhat common FAQ on the Python lists is why using live variables in 
default arguments doesn't do what you might expect.

I've never had this particular problem, strangely enough. If I have a list 
member in an object, it is usually set entirely at some point, instead of 
modified. If the list is integral, I usually subclass list to make the 
interface more natural.

-- 
James Oakley
[EMAIL PROTECTED]

-------------------------------------------------------------------------
This SF.net email is sponsored by: Microsoft
Defy all challenges. Microsoft(R) Visual Studio 2008.
http://clk.atdmt.com/MRT/go/vse0120000070mrt/direct/01/
_______________________________________________
Freevo-devel mailing list
Freevo-devel@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/freevo-devel

Reply via email to