python - Python 中没有构造函数重载——缺点?

标签 python

我正在浏览 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/

相关文章:

python - 如何将 matplotlib plot 设置为 "no fill"?

python - IPython Notebook中的Python OpenCV错误

python - Python 中的异常与错误

python - python中的日期格式不一致

python - 如果文件 1 中的术语在文件 2 的行中,则将文件 2 中的整行写入文件 3

python - 根据 Pandas 数据框中具有不同长度前缀和不一致分隔符的列值的公共(public)前缀对数据进行分组和求和

python - m2crypto:python 2.7 兼容性以及使用哪个版本的 OpenSSL?

python - 尝试使用 to_sql 函数插入时,数据库引擎无法连接到 sql-server 实例

python - pandas DataFrame.to_string() 从列中截断字符串

具有多个参数的 Python 多处理池映射