OO in Python? ^^

Martin Christensen martin.sand.christensen at gmail.com
Sat Dec 10 18:59:07 EST 2005


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

>>>>> "Matthias" == Matthias Kaeppler <void at void.com> writes:
Matthias> sorry for my ignorance, but after reading the Python
Matthias> tutorial on python.org, I'm sort of, well surprised about
Matthias> the lack of OOP capabilities in python. Honestly, I don't
Matthias> even see the point at all of how OO actually works in
Matthias> Python.

It's very common for Python newbies, especially those with backgrounds
in languages such as C++, Java etc. to not really 'get' the Python way
of handling types until they've had a fair amount of experience with
Python. If you want to program Pythonically, you must first unlearn a
number of things.

For instance, in e.g. the Java tradition, if a function needs a
triangle object, it'll take a triangle object as an argument. If it
can handle any type of shape, it'll either take a shape base class
instance as an argument or there'll be some kind of shape interface that
it can take. Argument types are strictly controlled. Not so with
Python. A Python solution will typically take any type of object as an
argument so long as it behaves as expected, and if it doesn't, we deal
with the resulting exception (or don't, depending on what we're trying
to accomplish). For instance, if the function from before that wants a
shape really only needs to call an area method, anything with an area
method can be used successfully as an argument.

Some have dubbed this kind of type check 'duck typing': if it walks
like a duck and quacks like a duck, chances are it'll be a duck. To
those who are used to (more or less) strong, static type checks, this
will seem a reckless approach, but it really works rather well, and
subtle type errors are, in my experience, as rare in Python as in any
other language. In my opinion, the tricks the C*/Java people
occasionally do to get around the type system, such as casting to the
fundamental object type, are worse because they're seldom expected and
resulting errors thus typically more subtle.

In my very first post on this news group a number of years ago, I
asked for an equivalent of Java's interfaces. The only reply I got was
that I didn't need them. While the reason was very obvious, even with
what I knew about Python, it still took a while to sink in. From what
I can tell, you're in somewhat the same situation, and the two of us
are far from unique. As I said in the beginning, Python newbies with a
background in statically typed languages typically have a lot to
unlearn, but in my opinion, it's well worth it.


Martin
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)
Comment: Using Mailcrypt+GnuPG <http://www.gnupg.org>

iEYEARECAAYFAkOba8oACgkQYu1fMmOQldXzcgCg0JEGTEG7xC/yAx8C1VFO8H1R
LWwAnRJ8AxHBe8YoHcDC5oGRfYaPHTfX
=HdTR
-----END PGP SIGNATURE-----



More information about the Python-list mailing list