from collections import namedtuple
Point = namedtuple('whatsmypurpose',['x','y'])
p = Point(11,22)
print(p)
输出:
whatsmypurpose(x=11,y=22)
的相关性/用途是'whatsmypurpose'
什么?
from collections import namedtuple
Point = namedtuple('whatsmypurpose',['x','y'])
p = Point(11,22)
print(p)
输出:
whatsmypurpose(x=11,y=22)
的相关性/用途是'whatsmypurpose'
什么?
namedtuple()
是tuple
子类的工厂函数。这里,'whatsmypurpose'
是类型名称。创建命名元组时,whatsmypurpose
会在内部创建一个具有此名称 ( ) 的类。
您可以通过使用详细参数来注意到这一点,例如:
Point=namedtuple('whatsmypurpose',['x','y'], verbose=True)
您也可以尝试type(p)
验证这一点。
'whatsmypurpose'
给新的子类它的类型名称。从文档:
collections.namedtuple( typename , field_names, verbose=False,rename=False)
返回一个名为typename的新元组子类。
这是一个例子:
>>> from collections import namedtuple
>>> Foo = namedtuple('Foo', ['a', 'b'])
>>> type(Foo)
<class 'type'>
>>> a = Foo(a = 1, b = 2)
>>> a
Foo(a=1, b=2)
>>> Foo = namedtuple('whatsmypurpose', ['a', 'b'])
>>> a = Foo(a = 1, b = 2)
>>> a
whatsmypurpose(a=1, b=2)
>>>
将verbose
参数设置为True
,可以看到完整的whatsmypurpose
类定义。
>>> Foo = namedtuple('whatsmypurpose', ['a', 'b'], verbose=True)
from builtins import property as _property, tuple as _tuple
from operator import itemgetter as _itemgetter
from collections import OrderedDict
class whatsmypurpose(tuple):
'whatsmypurpose(a, b)'
__slots__ = ()
_fields = ('a', 'b')
def __new__(_cls, a, b):
'Create new instance of whatsmypurpose(a, b)'
return _tuple.__new__(_cls, (a, b))
@classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
'Make a new whatsmypurpose object from a sequence or iterable'
result = new(cls, iterable)
if len(result) != 2:
raise TypeError('Expected 2 arguments, got %d' % len(result))
return result
def _replace(_self, **kwds):
'Return a new whatsmypurpose object replacing specified fields with new values'
result = _self._make(map(kwds.pop, ('a', 'b'), _self))
if kwds:
raise ValueError('Got unexpected field names: %r' % list(kwds))
return result
def __repr__(self):
'Return a nicely formatted representation string'
return self.__class__.__name__ + '(a=%r, b=%r)' % self
def _asdict(self):
'Return a new OrderedDict which maps field names to their values.'
return OrderedDict(zip(self._fields, self))
def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return tuple(self)
a = _property(_itemgetter(0), doc='Alias for field number 0')
b = _property(_itemgetter(1), doc='Alias for field number 1')
考虑:
class MyClass(tuple):
pass
这将创建一个type,它是一个元组子类,它有一个 name MyClass.__name__ == "MyClass"
。 namedtuple
是一个类型工厂,它还创建元组子类,但在这个功能 API 中,您必须显式传递名称。
当您将返回的类型分配给不同的名称时:
Point = namedtuple('whatsmypurpose',['x','y'])
它类似于这样做:
class whatsmypurpose(tuple):
... # extra stuff here to setup slots, field names, etc
Point = whatsmypurpose
del whatsmypurpose
在这两种情况下,您只是为该类型添加一个不同的名称。
通常,您会分配与类型名称相同的名称。如果您对重复相同的字符串不是DRY感到困扰,那么您可以使用 in 中的声明性 APItyping.NamedTuple
而不是 in 中的功能性 API collections
。然后,您可能会因为需要注释类型而烦恼。