我正在浏览 DiveIntoPython 并遇到了这个:
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.
子类的 __init__
方法将总是覆盖父类(super class)的 __init__
方法,这不是一个主要缺点吗?因此,如果我在类 class1
的 __init__
中初始化一些变量并调用一些函数,那么我将派生一个子类 class2(class1)
其中,我必须重新初始化所有 class1
的变量并在 class2
的 __init__
?
我很确定我误解了这一切,所以如果有人能澄清一下就太好了。
最佳答案
你是对的,在子类中定义 __init__
会覆盖父类(super class)的 __init__
,但你始终可以使用 super(CurrentClass, self).__init__
从子类调用父类(super class)的构造函数。因此,您不必“手动”重复父类(super class)的初始化工作。
作为旁注,即使 Python 不支持方法重载,它也支持默认参数(除了通过 *args
和 **kwargs
的可选参数) ,这意味着您可以通过简单地在函数/方法实现中接受不同的参数子集来轻松模拟重载函数的行为。
关于python - Python 中没有构造函数重载——缺点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13989304/