You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将待实例化对象列表传入自定义类完成实例化并按名称访问属性

解决方案

方案1:直接生成全局变量(实现helen.spent_on_cats优先需求)

核心是利用Python的全局命名空间字典globals()动态创建变量,修改后代码如下:

import pandas as pd

df = pd.DataFrame([['helen', 'peanut', 3],['helen', 'butter', 7],['agnes', 'tuna', 5]], columns=['registered_to', 'cat_name', 'sale_price'])

cat_owners = df.registered_to.unique()

class CatOwner():
    def __init__(self, name):
        self.name=name
        self.spent_on_cats = df.loc[df.registered_to==name]['sale_price'].sum()

# 动态生成以用户名命名的全局实例
for name in cat_owners:
    globals()[name] = CatOwner(name)

# 测试输出
print(helen.spent_on_cats) # 输出10
print(agnes.spent_on_cats) # 输出5

方案2:结构化容器访问(实现cat_owners.helen.spent_on_cats需求,无全局变量污染)

如果不想污染全局命名空间,可以用SimpleNamespace封装实例,实现属性式访问:

import pandas as pd
from types import SimpleNamespace

df = pd.DataFrame([['helen', 'peanut', 3],['helen', 'butter', 7],['agnes', 'tuna', 5]], columns=['registered_to', 'cat_name', 'sale_price'])

cat_owners_raw = df.registered_to.unique()

class CatOwner():
    def __init__(self, name):
        self.name=name
        self.spent_on_cats = df.loc[df.registered_to==name]['sale_price'].sum()

# 构建实例容器
cat_owners = SimpleNamespace(**{name: CatOwner(name) for name in cat_owners_raw})

# 测试输出
print(cat_owners.helen.spent_on_cats) # 输出10
print(cat_owners.agnes.spent_on_cats) # 输出5

如果不需要属性式访问,也可以直接用字典存储实例,调用方式为cat_owners['helen'].spent_on_cats,后续容器变更时调整成本更低。

内容的提问来源于stack exchange,提问作者holdyoucloser2003

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 14:36:00