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

如何在Python dataclasses中使用位置参数与可变位置参数

使用dataclass实现带固定参数和可变位置参数的类

要实现你需要的类,最直接的方式是在dataclass中自定义__init__方法,同时保留dataclass自动生成的__repr__、__eq__等便捷特性。具体代码如下:

from dataclasses import dataclass

@dataclass
class SomeClass:
    a: int
    b: int
    c: int
    other: tuple = ()  # 定义字段并设置默认空元组,避免dataclass抛出异常

    def __init__(self, a, b, c, *args):
        # 手动初始化固定参数和可变参数对应的字段
        self.a = a
        self.b = b
        self.c = c
        self.other = args

测试代码验证效果:

sample_object = SomeClass(1, 3, 5, 6, 7)
sample_object.other  # 结果为 (6, 7)
print(sample_object)  # 输出:SomeClass(a=1, b=3, c=5, other=(6, 7))

说明

  • dataclass允许自定义__init__方法,以此适配可变位置参数的需求,同时不影响其他自动生成方法的功能。
  • 提前定义other字段并设置默认空元组,是为了让dataclass识别该字段,确保生成的__repr__等方法能包含这个属性。
  • 这种写法既保留了原代码的参数逻辑,又充分利用了dataclass的便捷特性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 22:13:28