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

2024-10-01 07:29:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我想为一个对象的所有实例求和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个必需的位置参数。在


Tags: to对象实例selfget属性dictclass
1条回答
网友
1楼 · 发布于 2024-10-01 07:29:45

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

相关问题 更多 >