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
相关产品推荐
相关产品推荐

