Python and Schools

Alex Martelli aleax at aleax.it
Sun Apr 13 00:35:35 CEST 2003


Michael Robin wrote:
   ...
> class C:
>     x = 42
>     def foo(): self.x += 1

No doubt you intend foo to have a self argument, right?

> other way around?) - but in this case I think we'd vote for the extra
> typing for the class accessor, just as we don't mind "self.".

It's not a matter of extra typing, but of changing semantics!!!

>>> class C:
...   x = 42
...   def foo(self): self.x = self.x + 1
...
>>> class D:
...   x = 42
...   def foo(self): self.x = D.x + 1
...
>>> class subC(C): x = 23
...
>>> class subD(D): x = 23
...
>>> aa = subC(); aa.foo(); print aa.x
24
>>> aa = subD(); aa.foo(); print aa.x
43
>>>

See the difference?  By switching to D.x instead of self.x, you
inhibit the data override in class subD from working as intended --
you cannot any more make a subclass have a different default /
starting value for the x attribute of its instances that is
different from that in the base class.

You need to know which semantics you desire, but in most cases
allowing data overriding adds flexibility at no cost -- thus it's
what you should be doing by default.  Use self.attribute, NOT
someclass.attribute, even in methods written inside someclass,
in order to allow data overriding to work.


Furthermore, would you be happy calling aa.__class__.foo(), if
aa.foo didn't automatically go get the attribute from the class
when it doesn't find it in the instance?  I doubt so.  Automatic
delegation of attribute access from instance to class is THE
prime mechanism of Python's O-O, after all.  So what horrid kludges
would you suggest, to ensure that accessing self.x delegates to
the class (when instance self has no specific attribute x) just
in some cases but not in others...?

MUCH better as we have it today -- simpler, more practical,
more flexible, more regular and general -- ALWAYS delegate
the lookup when the attribute isn't found right in the instance.
How could piling exceptions on top of this simple rule make
things any better?!


Alex





More information about the Python-list mailing list