I am porting a project from Java to Python and there is a class with multiple constructors. I'm trying to port that same idea to python, in a pythonic way. I've recently been informed of the typing.overload decorator, but I can't seem to coerce the code to behave the way I wish. For example, if a Java class had the following constructor signatures:
public Foo(){}
public Foo(int number) {}
publid Foo(String b, float number) {}
public Foo(float number) {}
In Python, I tried to replicate that behavior with the following class definition:
class Foo():
@typing.overload
def __init__(self) -> None:
...
@typing.overload
def __init__(self, number: int) -> None:
...
@typing.overload
def __init__(self, string: str, number: float) -> None:
...
@typing.overload
def __init__(self, number: float) -> None:
...
def __init__(self, string: str = None, number: typing.Union[int,float] = None) -> None:
if isinstance(string, str):
print(f'String string: {string}')
elif isinstance(string, int):
print(f'String int: {string}')
elif isinstance(string, float):
print(f'String float: {string}')
elif isinstance(string, bool):
print(f'String bool: {string}')
else:
print(f'String None')
if isinstance(number, str):
print(f'Number string: {number}')
elif isinstance(number, int):
print(f'Number int: {number}')
elif isinstance(number, float):
print(f'Number float: {number}')
elif isinstance(number, bool):
print(f'Number bool: {number}')
else:
print(f'Number None')
if __name__ == '__main__':
test1 = TestClass(1.0)
print(f'\n')
test2 = TestClass(6)
print(f'\n')
test3 = TestClass('Test 3', 3.0)
print(f'\n')
test4 = TestClass('Test 4', True)
With the four instantiations, what I was expecting to see was:
String None
Number float: 1.0
String None
Number int: 6
String string: Test 3
Number float: 3.0
String string: Test 4
Number bool: True
What I got was:
String float: 1.0
Number None
String int: 6
Number None
String string: Test 3
Number float: 3.0
String string: Test 4
Number int: True
I realize that I won't necessarily get a 1:1 ability with Java's strict typing and Python's overloads only being there for type-checkers and no runtime enforcement. I just seem to be fundamentally missing something with how to actually implement an overloaded init the way I was envisioning.
I appreciate the responses, I think the original comment of using Class methods is an overall better approach.
I'm constrained in this project because the code is for beginner level programmers and it has to maintain a slight bit of parity between a Python, Java, and C++ implementation.
In the end, I just used forced kwargs to implement different constructor signatures. Not the pythonic way of doing things, but it ended up working.