gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:12:13 28 4
gpt4 key购买 nike

我想对一个对象的所有实例的 costum 属性求和。

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 个必需的位置参数。

最佳答案

要使用 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)

关于python - 如何对对象的所有实例的属性求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42777251/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com