Archive for February, 2009
I always liked python. It is a rather gentle language with many functional and Object-Oriented characteristics. I was always complaining about python’s Object-Oriented support, and i have a principle as a developer: “If you cannot implement something, do not offer it as a feature”.
Python violates this principle, because it allows developers to use multiple inheritance on a class but does not implement it correctly. Consider the following example:
class ParentOne: def __init__(self): print "Parent One says: Hello my child!" self.i = 1 def methodOne(self): print self.i class ParentTwo: def __init__(self): print "Parent Two says: Hello my child" class Child(ParentOne, ParentTwo): def __init__(self): print "Child Says: hello"
We have three classes, ParentOne, ParentTwo, and Child. The class Child inherits ParentOne and ParentTwo.
Normally each parent class should be initialised when the child class is initialised through a specified initialisation scheme. Python just do not initialise the parent classes. For example, if we create an instance of the class Child
c = Child()
… we will see in our screen the following output:
bkarak$ python example.py Child Says: hello
As we can see the __init__ method (aka the constructor) for each parent class is never executed. OOppss.
So, if the ParentOne init method declares a field named “i” (instance field) and the child tries to execute the method, we will end up with the following result:
bkarak$ python example.py
Child Says: hello
Traceback (most recent call last):
File "example.py", line 20, in
c.methodOne()
File "example.py", line 9, in methodOne
print self.i
AttributeError: Child instance has no attribute 'i'Ouch. This fact narrows down the usability of multiple inheritance to simple concatenation of methods with static methods. Really nicely done.
My advice is: “Avoid it, because you are not going to enjoy it”.
I do not really know if something is better implemented in Python 3.0. I will check it and write about it in the distant future.
