【问题标题】:Sum a list of object attributes汇总对象属性列表
【发布时间】:2015-07-01 09:43:19
【问题描述】:

我有一个类定义为

class MyClass(object):

    def __init__(self, value=0):
        self.value = value

    def __add__(self,other):
        return MyClass(self.value + other.value)

    __radd__ = __add__

我只想像这样对它们应用sum 函数:

a=MyClass(value=1)
b=MyClass(value=2)

c=[a,b]
print sum(c)  # should return a MyClass instance with value 3

正如this post 中所建议的那样。但是,会引发异常:

     15 
     16 c=[a,b]
---> 17 print sum(c)

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

我不明白为什么sum 函数要添加两种不同的类型。

【问题讨论】:

    标签: python list python-2.7


    【解决方案1】:

    sum 需要在某个地方开始;默认情况下,它从0 开始。所以它尝试的第一个操作是0 + MyClass(value=1),你还没有告诉它怎么做!

    因此,您有两种选择:

    1. 指定start(例如sum(c, MyClass()));或
    2. 告诉MyClass 如何处理向实例添加整数。

    后者可能看起来像:

    class MyClass(object):
    
        ...
    
        def __add__(self, other):
            try:
                return MyClass(self.value + other.value)  # handle things with value attributes
            except AttributeError:
                return MyClass(self.value + other)  # but also things without
    
        ...
    

    它可以让你跳过显式的start

    >>> sum([MyClass(1), MyClass(2)]).value
    3
    

    【讨论】:

      【解决方案2】:

      因为sum(iterable[, start]) sums start 和从左到右迭代的项目并返回总数。 start 默认为 0。

      你可以修改类

      class MyClass(object):
      
          def __init__(self, value=0):
              self.value = value
      
          def __add__(self, other):
              if (isinstance(other, MyClass)):
                  return MyClass(other.value + self.value)
              else:
                  return MyClass(other + self.value)
      
          __radd__ = __add__
      

      【讨论】:

      • 我明白了,谢谢!然后我需要通过设置来初始化我的总和: sum(c,MyClass(0))
      • @LongDoCao 这是解决问题的一种方法,是的。 MyClass 实例是否可以添加到整数中?
      • @jonrsharpe :在我的情况下不是,但无论如何这很高兴知道。谢谢。
      • @jonrsharpe 是的,对此感到抱歉,我接受了另一个答案,因为它刚刚出现在您的答案之前,并帮助我了解了该怎么做。我改变了接受的答案。干杯。
      猜你喜欢
      • 2017-02-06
      • 2017-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-13
      • 1970-01-01
      • 1970-01-01
      • 2016-11-21
      相关资源
      最近更新 更多