wannik
wannik

Reputation: 12756

overloading a method with different types in python

I'd like to overload a method move in a class Point

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def move(self, other_point):
        ...

    def move(self, x, y):
        ...

The following way is not meaningful because x will be a Point object if y is not provided.

    def move(self, x, y=None):
        if y is None:
            other = x
            self.x += other.x 
            self.y += other.y
        else:
            self.x += x
            self.y += y

I'm not happy with the parameter name in the following way either.

    def move(self, *param):
        if len(p) == 1:
            other = param[0]
            self.x += other.x 
            self.y += other.y
        else:
            self.x += param[0]
            self.y += param[1]

What is the best way to overload the method move?

Upvotes: 0

Views: 69

Answers (2)

Hai Vu
Hai Vu

Reputation: 40803

As far as design goes, I recommend against overloading. It is cleaner to have to separate methods:

def move_to_coordinate(self, x, y):
    # Do something

def move_to_point(self, other):
    self.move_to_coordinate(other.x, other.y)

This way, each function is clearly defined, easy to understand, easy to test. If you insist in overloading:

def move(self, x=None, y=None, other_point=None):
    # Validate: (x, y) and other_point should be mutually exclusive
    if (x is not None and y is not None) == bool(other_point is not None):
        raise ValueError('Specify either (x, y) or other_point')

    # Do something

Upvotes: 3

Roland Smith
Roland Smith

Reputation: 43573

Use keyword arguments:

def move(self, **kwargs):
   if 'point' in kwargs:
        self.x += kwargs['point'].x
        self.y += kwargs['point'].y
   elif 'x' in kwargs and 'y' in kwargs:
        self.x += float(kwargs['x'])
        self.y += float(kwargs['y'])
   else:
       raise KeyError("Either 'point' or 'x' and 'y' must be present")

Upvotes: 1

Related Questions