Python classes: Simplify?

Chris Angelico rosuav at
Thu Mar 22 12:10:53 CET 2012

On Thu, Mar 22, 2012 at 9:51 PM, Steven Lehar <slehar at> wrote:
> It seems to me that the Python class system is needlessly confusing. Am I
> missing something?
> 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. Furthermore, why not call the
> initialization function after the class name as is done in other languages?
> Isn't that the simplest conceptually? Demonstrating with the above example:

Why doesn't Python do things the way Java does? Because Python isn't
Java. Different language, different choices. :)

Methods are called with an explicit first argument (the object being
acted upon). Constructors need that argument too, even though it's not
given in the invocation. With your example alternate syntax:

> class Complex:
>     def Complex(realpart, imagpart):
>         Complex.r = realpart
>         Complex.i = imagpart

there's no way to distinguish between assigning to the newly-created
object's attributes and assigning to the class's own attributes.
Especially since the latter is a truly viable option in Python, this
can't be done; consequently, there needs to be either an explicit or
an implicit "self" argument (C++ does this with an implicit 'this'
pointer); the Python choice is to make it explicit.

There's really no reason to have the name of the constructor change
when the class is renamed. The way Python does things, you can rename
a class by changing just one thing, the "class Foo:" line. In C++, you
have to also rename all your constructors. And bear in mind, a class
is an object, same as any other:

>>> class Foo:
	def __init__(self,x):
	def speak(self):
		print("x = "+self.x)
>>> a=Foo("Hello")
>>> a.speak()
x = Hello
>>> Bar=Foo
>>> b=Bar("World")
>>> b.speak()
x = World

If the constructor is named the same as the class, how would this sort
of thing function?


More information about the Python-list mailing list