0

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)
martineau
  • 119,623
  • 25
  • 170
  • 301
nickeb96
  • 789
  • 1
  • 10
  • 16
  • You might want to look into classmethods: http://stackoverflow.com/questions/19305296/multiple-constructors-in-python-using-inheritance – Arjen Dijkstra Feb 12 '17 at 14:48
  • I already know about the whole classmethod/staticmethod semi-solution. I have it in my answer as an example of what I don't want. The link Duikboot attached and the link to the "duplicate" question do not answer my question. – nickeb96 Feb 12 '17 at 15:25

0 Answers0