namedtuple

  • Returns a new tuple subclass named typename.

Declaration

In [ ]:
from collections import namedtuple

Point = namedtuple('Point', ['x', 'y']) # define a type and its fields

p = Point(x=11, y=22) # Point(x=11, y=22)
# p = Point(11, 22)

# access fields
print (p[0], p[1]) # 11 22
x, y = p
print (x, y) # 11 22
print (p.x, p.y ) # 11 22

Methods

In [ ]:
# _make, makes a new instance from an existing sequence or iterable
t = [11, 22]
p = Point._make(t)

# _asdict, return a new OrderedDict which maps field names to their corresponding values
p._asdict() # OrderedDict([('x', 11), ('y', 22)])

# _replace, return a new instance of the named tuple replacing specified fields with new values
print(p)
p2 = p._replace(x=33)
print(p2) # Point(x=33, y=22)

# _fields, tuple of strings listing the field names
print(p._fields) # ('x', 'y')

Built-in Functions

In [ ]:
getattr(p, 'x') # 11

Define Class

In [35]:
class Point(namedtuple('Point', ['x', 'y'])):
    __slots__ = ()
    
    @property
    def hypot(self):
        return (self.x ** 2 + self.y ** 2) ** 0.5

    def __str__(self):
        return 'Point: x=%6.3f  y=%6.3f  hypot=%6.3f' % (self.x, self.y, self.hypot)
    
p = Point(1, 2)
print(p)
Point: x= 1.000  y= 2.000  hypot= 2.236