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

如何自动将__init__方法的参数赋值为Python类的实例属性?

自动将Python类__init__参数转为实例属性的几种方法

方法1:利用locals()简化赋值

直接遍历__init__内的局部变量,排除self后批量赋值给实例属性,新增参数无需手动修改赋值逻辑:

class Trainer:
    def __init__(self, model="unet", encoder_name="resnet18", encoder_weights="imagenet",
                 in_channels=3, num_classes=1, loss="jaccard",
                 ignore_index=0, learning_rate=1e4, learning_rate_schedule_patience=10,
                 ignore_zeros=True):
        # 自动赋值所有参数为实例属性
        for key, value in locals().items():
            if key != 'self':
                setattr(self, key, value)

注意:如果__init__内定义了其他局部变量,这些变量也会被赋值为实例属性,所以只适合参数全部需要转为属性的场景。

方法2:使用标准库dataclasses(Python3.7+)

官方推荐的轻量化方案,专为数据存储类设计,自动生成__init__、__repr__等方法,参数直接成为实例属性:

from dataclasses import dataclass

@dataclass
class Trainer:
    model: str = "unet"
    encoder_name: str = "resnet18"
    encoder_weights: str = "imagenet"
    in_channels: int = 3
    num_classes: int = 1
    loss: str = "jaccard"
    ignore_index: int = 0
    learning_rate: float = 1e4
    learning_rate_schedule_patience: int = 10
    ignore_zeros: bool = True

新增参数只需在类中添加字段即可,若需要自定义初始化逻辑,可以通过__post_init__方法补充。

方法3:使用第三方库attrs

适合需要复杂逻辑(如参数验证、类型转换)的场景,功能比dataclasses更丰富:
首先安装库:pip install attrs

import attr

@attr.define
class Trainer:
    model: str = "unet"
    encoder_name: str = "resnet18"
    encoder_weights: str = "imagenet"
    in_channels: int = 3
    num_classes: int = 1
    loss: str = "jaccard"
    ignore_index: int = 0
    learning_rate: float = 1e4
    learning_rate_schedule_patience: int = 10
    ignore_zeros: bool = True

支持参数验证、默认值设置、自定义转换器等功能,新增参数同样只需添加字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 01:40:27