python's sum() and non-integer values

前端 未结 6 1624
耶瑟儿~
耶瑟儿~ 2020-12-01 18:04

Is there a simple and quick way to use sum() with non-integer values?

So I can use it like this:

class Foo(object):
    def __init__(self,bar)
               


        
6条回答
  •  臣服心动
    2020-12-01 18:39

    Try using the __int__ method and then mapping each element in your list to the int function to get the values out:

    class Foo(object):
        def __init__(self,bar):
            self.bar = bar
        def __int__(self):
            return self.bar
    
    mylist = [Foo(3),Foo(34),Foo(63),200]
    result = sum(map(int,mylist))
    print(result)
    

提交回复
热议问题