【问题标题】:How to sum attributes of all instances of an object如何对对象的所有实例的属性求和
【发布时间】: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


【解决方案1】:

要使用 Python 中的 sum 内置函数作为对象的成员变量,您需要对对象的成员变量进行序列(例如,元组或列表)。下面的 sn-p 显示了如何制作对象成员变量的列表。您发布的代码省略了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)

【讨论】:

  • 没有解释,所以很遗憾它不会有帮助。这不是一个 sn-p 交易网站。
  • @TigerhawkT3 感谢您的建议。我把它解释得更清楚了。
猜你喜欢
  • 1970-01-01
  • 2015-04-30
  • 1970-01-01
  • 1970-01-01
  • 2016-11-27
  • 2023-04-05
  • 2016-06-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多