I was going through DiveIntoPython and came across this:
Java and Powerbuilder support function overloading by argument list, i.e. one class can have multiple methods with the same name but a different number of arguments, or arguments of different types. Other languages (most notably PL/SQL) even support function overloading by argument name; i.e. one class can have multiple methods with the same name and the same number of arguments of the same type but different argument names. Python supports neither of these; it has no form of function overloading whatsoever. Methods are defined solely by their name, and there can be only one method per class with a given name. So if a descendant class has an
__init__
method, it always overrides the ancestor__init__
method, even if the descendant defines it with a different argument list. And the same rule applies to any other method.
Isn't this a major disadvantage that a subclass's __init__
method will always override a superclass's __init__
method? So if I'm initializing some variables and calling some functions in a class class1
's __init__
, then I derive a subclass class2(class1)
of it, I'd have to reinitialize all of class1
's variables and call those functions in class2
's __init__
?
I'm pretty sure I'm misunderstanding all this, so it'd be great if someone clarifies this up.
Python supports neither of these; it has no form of function overloading whatsoever. Methods are defined solely by their name, and there can be only one method per class with a given name.
If we want to have different ways of initializing an object using different number of parameters, then we must do constructor overloading as we do method overloading when we want different definitions of a method based on different parameters.
In the python method and constructor, overloading is not possible.
But Python does not support function overloading. An error gets thrown if we implement the function overloading code the way we do in other languages. The reason is as Python does not have a data type for method parameters.
You're right that defining __init__
in a subclass overrides the superclass's __init__
, but you can always use super(CurrentClass, self).__init__
to call the superclass's constructor from the subclass. So, you don't have to "manually" duplicate the superclass's initialization work.
As a side note, even though Python doesn't support method overloading, it supports default arguments (in addition to optional arguments via *args
and **kwargs
), which means you can easily emulate the behavior of overloaded functions by simply accepting different subsets of arguments in your function/method implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With