【发布时间】:2017-08-04 06:33:08
【问题描述】:
我想对一个对象的所有实例的 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)
但我无法克服缺少 4 个必需的位置参数的 TypeError。
【问题讨论】:
-
第一个代码块向构造函数发送四个参数。第二个代码块发送零。你对其中一个是错的感到惊讶吗?您认为应该调查什么途径来解决它?
-
初始化新 Activity 对象时出现错误。您的课程要求您提供 4 个参数
costpool, costsum, costdriver, cdunits而您没有提供B.append(ActivityCenter())。否则它应该可以工作。
标签: python python-3.x python-object