简体   繁体   English

一个以上的构造函数 python class

[英]more than one constructor in a python class

I come from the Java programming language and I know that you can have more than one constructor there.我来自 Java 编程语言,我知道那里可以有多个构造函数。

My question now is: is that also possible in Python?我现在的问题是:Python 也可以吗?

My Problem:我的问题:

I have a class, where I have my help functions for my commands (implemented with click ).我有一个 class,其中有我的命令的帮助功能(通过click实现)。 These commands are not in the history class. Now my commands sometimes only have an input_dir and an output_file without a temp_file .这些命令不在历史记录中 class。现在我的命令有时只有一个input_dir和一个没有temp_fileoutput_file Or just an input_dir and output_file .或者只是一个input_diroutput_file

How can I still use the same constructor with 3 or sometimes 2 input parameters?我如何仍然使用具有 3 个或有时 2 个输入参数的相同构造函数?

There is no such thing as method overloading in python. Hence, it is impossible to have multiple constructors as you desire. python中没有方法重载。因此,不可能有多个构造函数。 You can however make the arguments optional.但是,您可以将 arguments 设为可选。

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'''

This will alow any combination of your arguments to work.这将允许您的 arguments 的任意组合起作用。 This would leave the method you are calling up to making sense of the instance's variables.这将使您正在调用的方法能够理解实例的变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM