Two attributes! Why?

Emanuele D'Arrigo manu3d at gmail.com
Fri Nov 28 22:22:42 EST 2008


Hi everybody,

I'm having a naming/scoping/mangling issue. I have a class like this:

class MyClass(object):
     __init__(self):
         self.__myAttribute = None

     def myMethod(self, aValue):
         attributeName = "__myAttribute"
         setattr(self, attributeName, aValue)

It all looks good to me but when I use a debugger I find that

- myClass._MyClass__myAttribute = None

and

- myClass.__myAttribute = aValue

I can't quite understand why. I was expecting to have the first
defined and having a value while I wasn't expecting to see the second
at all. And of course this is a problem because other methods are
trying to read the first variable and find it containing a None
object.

Admittedly, as I'm unit-testing the method I'm using the following
syntax to execute it directly from a test method:

myClass._MyClass__myMethod(aValue)

I guess this is not the "normal" way to do it as it would normally be
called from inside the object, like this:

self.__myMethod(aValue)

Is this what's causing the problem?

Thanks for your help.

Manu





More information about the Python-list mailing list