namedtuple TypeError位置参数的计数

时间:2019-02-05 19:22:01

标签: python namedtuple

如果namedtuple只调用两个,为什么TypeError消息会指示3个位置参数?为什么说给了4个?

from collections import namedtuple
Transition = namedtuple('Transition', ('one', 'two'))
a = Transition(1,2,3)
#TypeError: __new__() takes 3 positional arguments but 4 were given

2 个答案:

答案 0 :(得分:1)

实例方法的第一个参数始终是实例本身(通常命名为self。调用Transition(1,2)就是Transition.__new__(self, 1, 2)

*编辑:感谢@Slam指出namedtuple使用__new__而不是__init__

答案 1 :(得分:0)

重现您的错误

import collections

# Two-way construct numedtuple
# 1st way:use iterable object as 2nd paras
Transition01 = collections.namedtuple('Transition', ['one', 'two'])
# 2nd way:use space-splited string as 2nd paras
Transition02 = collections.namedtuple('Transition', 'one two')

# In order to figure out the field names contained in a namedtuple object, it is recommended to use the _fields attribute.
print(Transition01._fields)
print(Transition01._fields == Transition02._fields)

# After you know the field name contained in a namedtuple object, it is recommended to initialize the namedtuple using keyword arguments because it is easier to debug than positional parameters.
nttmp01 = Transition01(one=1, two=2)
nttmp02 = Transition01(1, 2)
print(nttmp01)
print(nttmp02)

调试信息

=====================================

# Transition01(1, 2, 3)
# Traceback (most recent call last):
# TypeError: __new__() takes 3 positional arguments but 4 were given

======================================

您关注的技术细节

function namedtuple_Transition.Transition.__new__(_cls, one, two)

分析: 创建的命名元组类对象具有内部实现方法 new ,由定义该方法的工程师采用调用者对象作为方法的第一个参数,这是一种更常见的类方法定义形式。