What is a clean "pythonic" way to implement multiple constructors?
A "pythonic" way to implement multiple constructors in Python is to use the @classmethod
decorator. A class method is a method that is bound to the class and not the instance of the object.
Here is an example:
class MyClass:
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
@classmethod
def from_input_string(cls, input_string: str):
arg1, arg2 = input_string.split(',')
return cls(arg1, arg2)
@classmethod
def from_config_file(cls, file_path: str):
with open(file_path) as f:
config = json.load(f)
return cls(config['arg1'], config['arg2'])
You can then use the class methods as alternative constructors by calling MyClass.from_input_string("hello,world")
or MyClass.from_config_file("path/to/config.json")