【问题标题】:How to properly overwrite __add__ method and create new object in Python?如何正确覆盖 __add__ 方法并在 Python 中创建新对象?
【发布时间】:2020-11-18 18:27:12
【问题描述】:

所以我写了一个愚蠢的示例类:

class Pair:

    def __init__(self, x, y):
        self._x = x
        self._y = y

    # add two objects of type Paar
    def __add__(self, other):
        new_x = self._x + other._x
        new_y = self._y + other._y
        
        # better this?
        self._x = new_x
        self._y = new_y
        return self

        # or this?
        # return Paar(new_x, new_y)

现在我想添加这个类的两个实例,我只是有点卡在我的脑海里。这两个选项中的哪一个更适合使用?

【问题讨论】:

  • 你的实现 returns self 不好(至少,它违反约定),__add__ 挂钩到 +,通常应该改变它的参数.为此,请使用与+= 挂钩的__iadd__。所以你只需要return Paar(new_x, new_y)
  • 非常感谢!这澄清了很多:)

标签: python class operator-overloading


【解决方案1】:

第一个解决方案是第二个(已评论)。在第二个中,您返回该类的一个新实例,而在第一个中,您就地修改第一个实例,这不是预期的行为。 为了说明问题:

class Pair_v1:

    def __init__(self, x, y):
        self._x = x
        self._y = y

    # add two objects of type Pair
    def __add__(self, other):
        new_x = self._x + other._x
        new_y = self._y + other._y
        return Pair_v1(new_x, new_y)


# Create two instances of Pair
pair1 = Pair_v1(2.0, 5.0)
pair2 = Pair_v1(7.0, 2.7)

# Add pair1 to pair2
pair1 += pair2

print('x = {}'.format(pair1._x))
print('y = {}'.format(pair1._y))

# Create a third instances as the sum of the two previous
pair3 = pair1 + pair2

print('In this case, pair1 IS NOT modified when creating pair3 (expected behavior).')
print('x = {}'.format(pair1._x))
print('y = {}'.format(pair1._y))
print('\n')

class Pair_v2:

    def __init__(self, x, y):
        self._x = x
        self._y = y

    # add two objects of type Pair
    def __add__(self, other):
        self._x += other._x
        self._y += other._y
        
        return self
    
# Create two instances of Pair
pair1 = Pair_v2(2.0, 5.0)
pair2 = Pair_v2(7.0, 2.7)

# Add pair1 to pair2
pair1 += pair2

print('x = {}'.format(pair1._x))
print('y = {}'.format(pair1._y))

# Create a third instances as the sum of the two previous
pair3 = pair1 + pair2

print('In this case, pair1 IS modified when creating pair3 (unexpected behavior)')
print('x = {}'.format(pair1._x))
print('y = {}'.format(pair1._y))

【讨论】:

  • @RobinKohrs 他的解决方案不正确。当您执行pair3 = pair1 + pair2时,它确实修改pair1
  • 当然,正确的形式是注释的形式(上例中的pair_v1)。
猜你喜欢
  • 1970-01-01
  • 2023-01-11
  • 1970-01-01
  • 1970-01-01
  • 2019-11-14
  • 2021-10-16
  • 1970-01-01
相关资源
最近更新 更多