小编pie*_*uez的帖子

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

我想对一个对象的所有实例的 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"))
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经尝试使用 sum() 进行如下理解,参考这个解决方案

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

s = sum(i.costsum for i in B)
Run Code Online (Sandbox Code Playgroud)

但是我无法克服缺少 …

python python-3.x python-object

1
推荐指数
1
解决办法
2813
查看次数

标签 统计

python ×1

python-3.x ×1

python-object ×1