如何对对象的所有实例的属性求和

时间:2017-03-14 03:25:52

标签: python python-3.x python-object

我想总结一个对象的所有实例的costsum属性。

class ActivityCenter:

    def __init__(self, costpool, costsum, costdriver, cdunits):
        self.costpool = costpool
        self.costsum = costsum
        self.costdriver = costdriver
        self.cdunits = cdunits

cp1 = ActivityCenter("Material Handling", 480000, "Pounds", 160000)
cp2 = ActivityCenter("Production orders", 90000, "Num of POs", 200)

# I am looking to add up the costsum values for all instances, similar to:
costsumtotal = (cp1.__dict__.get("costsum")) + (cp2.__dict__.get("costsum"))

到目前为止,我已尝试使用sum()进行理解,如下所示:this solution

B = []
for i in range(10):
    B.append(ActivityCenter())

s = sum(i.costsum for i in B)

但是我在克服TypeError时遇到了麻烦,我错过了4个必需的位置参数。

1 个答案:

答案 0 :(得分:1)

要在Python中使用sum内置函数作为对象的成员变量,您需要创建对象的成员变量的序列(例如,元组或列表)。以下代码段显示了如何制作对象列表'成员变量。您发布的代码省略了comprehension expression。我希望它会有所帮助:))

class ActivityCenter:

    def __init__(self, costpool, costsum, costdriver, cdunits):
        self.costpool = costpool
        self.costsum = costsum
        self.costdriver = costdriver
        self.cdunits = cdunits

"""
Create some objects

objs = []
for i in range(num_obj):
    objs.append(ActivityCenter(<some value>,<...>,<...>,<...>))

Or use objects to make a list
"""
cp1 = ActivityCenter("Material Handling", 480000, 160000, "Pounds")
cp2 = ActivityCenter("Production orders", 90000, 200, "Num of POs")
cp3 = ActivityCenter("Marketing", 120000, 1000, "Num of events")

objs = [cp1, cp2, cp3]

total_cost = sum([obj.costsum for obj in objs])  # List comprehension
print("Total cost: ", total_cost)