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

从字典创建对象时转换指定字段类型的方法

解决方法

可以通过定义转换规则+批量处理的方式实现,不用为每个属性重复写转换代码,下面提供两种实用方案:

方案一:用数据类(dataclass)自动识别类型转换

适合Python 3.7+版本,利用数据类的类型注解来自动判断哪些字段需要转为float:

from dataclasses import dataclass

@dataclass
class MyObject:
    # 直接在注解里声明字段类型:float需要转换,str保持原类型
    key1: float
    key2: str
    key3: float
    # 继续添加其他属性...

    @classmethod
    def from_dict(cls, data_dict):
        processed = data_dict.copy()
        # 遍历所有注解字段,自动转换类型
        for field, field_type in cls.__annotations__.items():
            if field_type is float and field in processed:
                processed[field] = float(processed[field])
        return cls(**processed)

# 使用示例
d = {'key1': '12.3', 'key2': 'hello', 'key3': '45.6'}
obj = MyObject.from_dict(d)
print(obj.key1, type(obj.key1))  # 输出:12.3 <class 'float'>
print(obj.key2, type(obj.key2))  # 输出:hello <class 'str'>

只要在类注解里声明好字段类型,后续新增属性时只需要加注解,不用修改转换逻辑。

方案二:普通类+转换字段集合

如果不想用dataclass,直接定义普通类,维护一个需要转float的字段集合即可:

class MyObject:
    # 把需要转为float的字段放在这个集合里,新增字段直接加进来
    FLOAT_FIELDS = {'key1', 'key3'}

    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            if key in self.FLOAT_FIELDS:
                # 可选:加异常处理,避免非数字字符串转换失败
                try:
                    setattr(self, key, float(value))
                except ValueError:
                    # 转换失败时可以选择保留原字符串/设默认值/抛出异常
                    setattr(self, key, value)
            else:
                setattr(self, key, value)

# 使用示例
d = {'key1': '12.3', 'key2': 'hello', 'key3': '45.6'}
obj = MyObject(**d)
print(obj.key1, type(obj.key1))  # 输出:12.3 <class 'float'>
print(obj.key2, type(obj.key2))  # 输出:hello <class 'str'>

这种方式更灵活,不需要依赖dataclass,只需要维护FLOAT_FIELDS集合就能批量控制转换逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 10:01:16