在python

时间:2015-08-13 02:09:01

标签: python python-3.x

我想在课程

中重载方法移动
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def move(self, other_point):
        ...

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

以下方式没有意义,因为如果没有提供y,x将是 Point 对象。

    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

我对参数名称也不满意。

    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]

重载方法移动的最佳方法是什么?

2 个答案:

答案 0 :(得分:3)

就设计而言,我建议不要超载。必须分开方法更清晰:

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

def move_to_point(self, other):
    self.move_to_coordinate(other.x, other.y)
这样,每个功能都明确定义,易于理解,易于测试。如果你坚持超载:

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

答案 1 :(得分:1)

使用关键字参数:

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