OO in Python? ^^
bdesth.quelquechose at free.quelquepart.fr
Sun Dec 11 21:57:50 CET 2005
Matthias Kaeppler a écrit :
> sorry for my ignorance, but after reading the Python tutorial on
> python.org, I'm sort of, well surprised about the lack of OOP
> capabilities in python.
I beg your pardon ???
> Honestly, I don't even see the point at all of
> how OO actually works in Python.
> For one, is there any good reason why I should ever inherit from a
To specialize it (subtyping), or to add functionnalities (code reuse,
> ^^ There is no functionality to check if a subclass correctly
> implements an inherited interface
I don't know of any language that provide such a thing. At least for my
definition of "correctly".
> and polymorphism seems to be missing
> in Python as well.
Could you share your definition of polymorphism ?
> I kind of can't imagine in which circumstances
> inheritance in Python helps. For example:
> class Base:
> def foo(self): # I'd like to say that children must implement foo
raise NotImplementedError, "please implement foo()"
> class Child(Base):
> pass # works
> Does inheritance in Python boil down to a mere code sharing?
Yes. inheritence is initially made for code sharing (cf Smalltalk). The
use of inheritence for subtyping comes from restrictions of statically
typed languages . BTW, you'll notice that the GoF (which is still one
of the best references about OO) strongly advise to program to
interfaces, not to implementations. And you'll notice that some patterns
only exists as workarounds for the restrictions enforced by statically
 should say : for *a certain class of* statically typed languages.
There are also languages like OCaml that relies on type inference.
> And how do I formulate polymorphism in Python?
In OO, polymorphism is the ability for objects of different classes to
answer the same message. It doesn't imply that these objects should
inherit from a common base class. Statically typed languages like C++ or
Java *restrict* polymorphism.
You don't need any of this.
print "%s walk" % self.__class__.__name__
print "I'm singing in the rain"
f = Foo()
b = Bar()
Here, the function (BTW, did you know that in Python, functions are
objects too ?) letsgoforawalk expect an object that has the type 'object
that understand the message walk()'. Any object of this type will do -
no need to have a common base class.
> I could as well leave the whole inheritance stuff out and the program
> would still work (?).
Of course. Why should polymorphism need anything more ?
> Please give me hope that Python is still worth learning :-/
It is, once you've unlearned C++/Java/ADA/whatever.
More information about the Python-list