我想为一个对象的所有实例求和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:
^{pr2}$但是我很难克服类型错误,我缺少4个必需的位置参数。在
要利用Python中的
sum
内置函数来处理对象的成员变量,需要对对象的成员变量进行一个序列(例如,元组或列表)。下面的代码片段演示如何生成对象的成员变量列表。您发布的代码省略了comprehension expression。希望能有所帮助:)相关问题 更多 >
编程相关推荐