How do you overload functions in Python? I know about default arguments, but what if you want one version of a function to take one type and another version to take a different type. In some cases it is easier to write two different functions with different names like from_int and from_str, but this is not always viable in certain cases like the _init_ method.
A simple example:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __init__(self, point):
self.x = point.x
self.y = point.y
Obviously this would not work since there are two definitions of the same function.
I have looked at other questions on SO about overloading functions, but most of them refer to using default arguments and I don't think that would work in this case especially if I wanted to use default arguments for a different purpose. Lets say I wanted the first constructor to set x and y to zero if nothing was given: _init_(x=0,y=0)
This would become even more problematic if I wanted a third version of _init_ to init both x and y from one scalar value:
def __init__(self, n):
self.x = n
self.y = n
In C++ these constructors would be trivial to implement but I do not know of a clean way to do it in python.
I thought about doing this but it does not seem very clean to call:
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
@staticmethod
def from_pair(x, y):
return Point(x, y)
@staticmethod
def from_single(n):
return Point(n, n)
@staticmethod
def from_point(point):
return Point(point.x, point.y)