如何在类实例上正确执行算术?例如。将House类实例列表的n_people属性求和

时间:2019-04-10 02:33:55

标签: python python-3.x class instance-variables

如何在类实例上正确执行算术?在下面的示例中,该类表示House,并包含一个n_people属性,该属性表示该房屋中的人数。

目标是对House类实例求和,并返回房屋总数。将House类实例添加在一起时,这似乎起作用:

class House:

    def __init__(self, n_people):
        self.n_people = n_people

    def __add__(self, n_people):
        return n_people + self.n_people

House(3) + House(4)

在对House类实例的数组求和时失败:

houses = [House(i) for i in range(10)]
sum(houses)

产生的错误是:

TypeError                                 Traceback (most recent call last)
<ipython-input-66-197f26932b89> in <module>
      1 houses = [House(i) for i in range(10)]
----> 2 sum(houses)

TypeError: unsupported operand type(s) for +: 'int' and 'House'

在Python中对类实例执行算术运算的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

您面临的问题是sum从左到右起作用,因此在对前两个House实例求和后,您的代码会尝试执行int + House House + int被定义。

要解决此问题,您需要定义__radd__,在这种情况下会被调用:

class House:

    def __init__(self, n_people):
        self.n_people = n_people

    def __add__(self, n_people):
        return n_people + self.n_people

    def __radd__(self, n_people):
        return n_people + self.n_people

House(3) + House(4)
houses = [House(i) for i in range(10)]
sum(houses)

输出:

45