0

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?

Shalomi90
  • 736
  • 4
  • 9
  • 33
  • Does this answer your question? [What is a clean, pythonic way to have multiple constructors in Python?](https://stackoverflow.com/questions/682504/what-is-a-clean-pythonic-way-to-have-multiple-constructors-in-python) – Random Davis Sep 22 '20 at 15:23
  • 4
    Python does not have overloading, so there is only ever a single `__init__`. In this particular case, I would just use default values in your `__init__` – juanpa.arrivillaga Sep 22 '20 at 15:26
  • Besides using default argument values (the most straightforward way), you can also use `*args`, `**kwargs`, or `from multipledispatch import dispatch`: https://pypi.org/project/multipledispatch/ – JacobIRR Sep 22 '20 at 15:30

1 Answers1

1

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.

Shine
  • 676
  • 6
  • 12