namedtuple TypeError位置参数计数

问题描述 投票:0回答:2

如果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
python namedtuple
2个回答
1
投票

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

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


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的内部实现方法,定义该方法的工程师将方法调用者对象作为方法的第一个参数,这是一种更常见的类方法定义形式。

© www.soinside.com 2019 - 2024. All rights reserved.