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

如何通过参数动态获取Owner模型的指定字段值?

问题

我希望通过参数动态获取Owner模型实例中对应列的数值,但直接用owner.assetType会把assetType当作属性而非参数处理,导致报错。以下是示例代码:

# Owner默认拥有1套住宅、2艘船、3辆车
class Owner(BaseTable):
    homes = IntegerField(null=False, default = 1)
    boats = IntegerField(null=False, default = 2)
    cars = IntegerField(null=False, default = 3)

owner = Owner.get_by_id(1)

allAssets = {
    "House1": {
        "assetType": "homes"
    },
    "Boat1": {
        "assetType": "boats"
    }
}

# 返回字符串'homes'
House1Type = allAssets["House1"].get("assetType")

# 正常输出1
print(owner.homes)

# 报错:AttributeError: 'Owner' object has no attribute 'assetType'
def findValue(assetType):
    print(owner.assetType)

# 期望输出1
findValue(House1Type)

目前我只能靠大量if-else语句实现需求,想找更简洁的方式:

# 根据assetType值动态获取对应属性
if House1Type == "boats":
    print("Owned Boats: ",owner.boats)
elif House1Type == "homes":
    print("Owned Homes: ",owner.homes)
else:
    pass
简洁的动态取值方案

用Python内置的getattr()函数就能实现动态属性取值,无需编写冗余的if-else分支。该函数支持通过字符串形式的属性名,直接从对象中获取对应属性值。

修改后的findValue函数如下:

def findValue(assetType):
    # 从owner对象中获取对应assetType名称的属性值
    value = getattr(owner, assetType)
    print(value)

# 调用后输出1,符合预期
findValue(House1Type)

如果要提升代码健壮性,可添加默认值或异常处理,避免传入不存在的属性名时触发报错:

def findValue(assetType):
    # 第三个参数为默认值,属性不存在时返回该值
    value = getattr(owner, assetType, None)
    if value is not None:
        print(value)
    else:
        print(f"不存在类型为{assetType}的资产")

# 测试不存在的属性
findValue("planes")  # 输出:不存在类型为planes的资产

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 17:05:21