Python classes: Simplify?

Chris Rebert clp2 at rebertia.com
Thu Mar 22 07:17:35 EDT 2012


On Thu, Mar 22, 2012 at 3:51 AM, Steven Lehar <slehar at gmail.com> wrote:
> It seems to me that the Python class system is needlessly confusing. Am I
> missing something?

Explicit `self` is slightly annoying, but you'll get over it quickly (trust me).

> For example in the class Complex given in the documentation
>
> class Complex:
>     def __init__(self, realpart, imagpart):
>         self.r = realpart
>         self.i = imagpart
>
> x = Complex(3.0, -4.5)
>
> I initially found it profoundly confusing that __init__( ) calls for 3
> arguments, but you call Complex( ) with 2.

That's not at all unique to __init__().

> Furthermore, why not call the
> initialization function after the class name as is done in other languages?

Yech. That would add another step to renaming a class and make
referring to the superclass initializer method rather difficult. It
would also break the "all special methods have underscored names"
rule.

Perhaps you'll find the following instructive:
Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53)
>>> class Foo(object):
...     def __init__(self):
...         pass
...
>>> Foo()
<__main__.Foo object at 0x100fd5750>
>>> Bar = Foo
>>> Bar.__name__ = "Bar"
>>> del Foo
>>> # look Ma, I've renamed the class!
>>> Bar()
<__main__.Bar object at 0x100fd57d0>

How would your scheme account for this possibility?

> Isn't that the simplest conceptually? Demonstrating with the above example:
>
> class Complex:
>     def Complex(realpart, imagpart):
>         Complex.r = realpart
>         Complex.i = imagpart

Your change of "self" to "Complex" in the method body here makes no sense to me.

> x = Complex(3.0, -4.5)
>
> Is there a good reason why classes cannot be defined that way? (Besides the
> problem of backward-compatibility)

Mostly historical, IMO. But here are some justifications for explicit `self`:
http://docs.python.org/faq/design.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls
http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html

Cheers,
Chris R.
--
http://blog.rebertia.com



More information about the Python-list mailing list