You need to enable JavaScript to run this app. Python中__init__的可变参数arglist为何是元组而非列表?
优惠活动
大模型
产品
解决方案
定价
更多

Python中__init__的可变参数arglist为何是元组而非列表?

这是Python的预期行为。
Python 中使用*参数名语法接收任意数量的位置参数时,解释器会自动将传入的多个参数打包为*元组(tuple)*赋值给该参数,该设计是Python语法的固有规则,你的代码本身不存在编写错误。

如果你希望self.arglist的类型为列表(list),仅需要在赋值时做一次类型转换即可,将原来的self.arglist = arglist替换为以下代码:

self.arglist = list(arglist)

修改后的完整参考代码:

class SMemberImpl():
    """docstring for SMemberImpl"""
    def __init__(self, *arglist):
        print(f"initializing SMemberImpl arglist={arglist} of type {type(arglist)}")
        super(SMemberImpl, self).__init__()
        self.arglist = list(arglist)
        print(f"self.arglist type is now {type(self.arglist)}")

    #... stuff omitted

class SMember(SMemberImpl):
    pass

调用SMember(1,2,3)测试时,self.arglist就会得到类型为list的[1,2,3]。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 20:15:04