total idiot question: +=, .=, etc...

Jesse Sweeney jesse at student.usyd.edu.au
Fri Jun 25 02:16:13 EDT 1999


On 23 Jun 1999 20:56:41 -0500, neelk at brick.cswv.com (Neel Krishnaswami) wrote:

[ snip -- complaints about having to write 'self' over and over ]

>I don't mind writing self.foo = bar, for the reason you describe, but
>I know I hate having to write self.__class__.member = foo in order to
>keep inheritance from breaking:
>
>class Foo:
>    x = 9
>    def munge_x(self, x):
>        Foo.x = x
>
>class Bar(Foo):
>    x = 12
     ^^^
     This creates an attribute Bar.x

>
>>>> a = Foo()
>>>> a.munge_x(15)
>>>> print a.x
>15
>
>>>> y = Bar()
>>>> y.munge_x(15)
>>>> print y.x
>12
^^^
Here, y.x evaluates to Bar.x

The problem is that a call to munge_x is munging Foo.x no matter what the self
parameter turns out to be. So, if self is an object with it's own x attribute,
whether as an instance attribute, or as a class attribute lower down in the
heirarchy, that attribute will mask the attribute of the same name in Foo (sorry
about that long sentence). ie: self.x isn't always the same as Foo.x.
    I don't really see what's unintuitive about this. You could just write:

        class Bar(Foo):
            pass

>
>But if I change Foo to:
>
>class Foo:
>    x = 9
>    def munge_x(self, x):
>        self.__class__.x = x
>
>and try the same thing, I get the more intuitive:
>
>>>> a = Foo()
>>>> a.munge_x(15)
>>>> print a.x
>15
>
>>>> y = Bar()
>>>> y.munge_x(15)
>>>> print y.x
>15

This is a different kettle of fish. Note:

>>> a = Foo()
>>> a.munge_x(15)
>>> a.x
15
>>> y = Bar()
>>> y.munge_x(20)
>>> y.x
20
>>> a.x
15

>
>It's just that writing self.__class__ is so *ugly*! Everything else
>in Python is beautiful, too, which makes this stand out even more. 

	Cheers, Jesse





More information about the Python-list mailing list