I come from the Java programming language and I know that you can have more than one constructor there.
My question now is: is that also possible in Python?
My Problem:
I have a class, where I have my help functions for my commands (implemented with 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
. Or just an input_dir
and output_file
.
How can I still use the same constructor with 3 or sometimes 2 input parameters?
Advertisement
Answer
There is no such thing as method overloading in python. Hence, it is impossible to have multiple constructors as you desire. You can however make the arguments optional.
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. This would leave the method you are calling up to making sense of the instance’s variables.