python class 中有多个构造函数

more than one constructor in a python class

我来自 Java 编程语言,我知道那里可以有多个构造函数。

我现在的问题是:在 Python 中也可以吗?

我的问题:

我有一个 class,其中有我的命令的帮助功能(使用 click 实现)。这些命令不在历史记录中 class。现在我的命令有时只有 input_diroutput_file 而没有 temp_file。或者只是 input_diroutput_file.

我如何仍然使用具有 3 个或有时 2 个输入参数的相同构造函数?

python中没有方法重载这样的东西。因此,您不可能拥有多个构造函数。但是,您可以将参数设为可选。

class History():
    def __init__(self, input_dir=None, output_file=None, temp_file=None):
        self._input_dir = input_dir
        self._output_file = output_file
        self.temp_file = temp_file

    def identify_ID(self):
        '''Identifies the ID'''

这将允许您的参数的任意组合起作用。这将使您正在调用的方法能够理解实例的变量。