[Tutor] Poorly understood error involving class inheritance

Wayne srilyk at gmail.com
Mon Oct 5 23:39:38 CEST 2009

On Mon, Oct 5, 2009 at 3:41 PM, David Perlman <dperlman at wisc.edu> wrote:

> OK, I thought I had this one fixed but it was weirder than I thought.  I
> think I understand what's going on, but I wanted to check with the experts
> here.
> I have the following class definition, which does not subclass anything:
> class oneStim:
>    def __init__(self, time, mods=[], dur=None, format='%1.2f'):
>        self.time=time
>        self.mods=mods

I think this is where the fun occurs (AFAIK, I'm not an expert on how the
python lists/namespaces work by any means)

You are familiar with the following concept/behavior, correct?

def f1(mylist):

a = [1,2]
>>> f1(a)
>>> a
[1, 2, 3]

because python doesn't actually pass a copy, just the reference of the list.
So I'm betting that when you say

self.mods = mods

the second time you call the function you're creating a reference to the
self.mods that's in the oneStim object namespace.

Ahhh... After some experimentation, I think I see what's going on.

class A:
    def __init__(self, mylist = []):
        self.mylist = mylist

a = A()
b = A()

In [69]: a.__init__.im_func
Out[69]: <function __init__ at 0x95888ec>

In [70]: A.__init__.im_func
Out[70]: <function __init__ at 0x95888ec>

In [71]: b.__init__.im_func
Out[71]: <function __init__ at 0x95888ec>

The function is at the same address for the parent class and each instance
of the class, so I think the reference it creates is to the list in the same
location as well.
Ah... some enlightenment has struck with what bob posted.

The "initial value" of that function is the /exact same/ each time the
function is called. When you pass a parameter to the function it will be
re-evaluated, but until then the pre-stored reference is used.

I'm not sure if that's terribly clear or makes much sense, it's a bit of a
difficult concept to wrap my head around, but I *think* I've got it.

Hopefully you can get it, too,
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091005/41f8de9b/attachment.htm>

More information about the Tutor mailing list