【问题标题】:Summing class instances [duplicate]总结类实例[重复]
【发布时间】:2014-02-21 13:33:34
【问题描述】:

我正在尝试在对象列表上使用内置函数sum() 并获取对象。

这是我的代码摘录:

class vector:

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

    def __add__(self, other):
        return vector(self.x+other.x, self.y+other.y)

l = []
l.append(vector(3, 5))
l.append(vector(-2, 3))
l.append(vector(0,-4))

net_force = sum(l)

我得到错误:

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

我猜这是因为 sum() 最初将结果设置为 0,然后遍历列表,但我只能定义向 vector 添加内容,而不是相反。

【问题讨论】:

  • 为什么要在__add__()-函数中新建vector-object?为什么不self.x += other.x; self.y+=orther.y
  • @msvalkon 因为那是完全错误的。您不希望a = b + c 修改b,而是希望它创建一个新向量并将其命名为a。你可能会想到__iadd__
  • 啊,是的,当然,对不起。

标签: python object sum


【解决方案1】:

设置你的起始条件(见Python documentation):

net_force = sum(l, vector(0, 0))

【讨论】:

    【解决方案2】:

    您的另一个选择是将__add__ 稍微修改为特殊情况,即

    class vector(object):
    
        def __init__(self, x, y):
            self.x = x
            self.y = y
    
        def __add__(self, other):
            if other == 0:
                return self
            else:
                return vector(self.x+other.x, self.y+other.y)
    

    这将使sum 在不指定初始条件的情况下工作......

    【讨论】:

      【解决方案3】:

      你可以这样做:

      net_force = vector(0,0)
      for i in l:
          net_force += i
      

      否则也许你可以找到你的答案here

      【讨论】:

      • 它可以工作,但它并不完全是pythonic。不过,感谢您提到__radd__ 的帖子。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-25
      • 1970-01-01
      • 1970-01-01
      • 2012-01-16
      相关资源
      最近更新 更多