0

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?

1
  • I would say the first method, python names are not bound to a type, and I do not think it would be good to bind them to a type either. Commented Aug 13, 2015 at 2:15

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.