繁体   English   中英

在python中重载具有不同类型的方法

[英]overloading a method with different types in python

我想重载类Point中的方法移动

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]

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

就设计而言,我建议不要过载。 不得不使用单独的方法会更干净:

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

使用关键字参数:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM