namedtuple
Declaration
Returns a new tuple subclass named typename
namedtuple is immutable
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y']) # define a type and its fields
p = Point(x=11, y=22)
#p = Point(11, 22)
# access
x, y = p # unpack like a regular tuple
print(x, y)
print(p[0], p[1]) # Access by index
print(p.x, p.y) # Access by keyname
print(getattr(p, 'x'), getattr(p, 'y')) # Access Using getattr
print('x is {}, y is {}'.format(*p))
Methods
# _make, makes a new instance from an existing sequence or iterable
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y']) # define a type and its fields
l = [11, 22]
p = Point._make(l)
# _asdict, return a dict which maps field names to their corresponding values
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y']) # define a type and its fields
p = Point(x=11, y=22)
d = p._asdict() # dict
# **, convert a dictionary into the namedtuple
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y']) # define a type and its fields
d = {'x':11, 'y':22}
p = Point(**d)
# _fields, get all the keynames of a namedtuplefrom collections import namedtuple
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y']) # define a type and its fields
p = Point(x=11, y=22)
print(p._fields) # ('x', 'y')
# _replace, return a new instance of the named tuple replacing specified fields with new values
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y']) # define a type and its fields
p = Point(x=11, y=22)
p2 = p._replace(x=33)
print(p2)
# __new__, returns a new instance with assigned values to keys
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y']) # define a type and its fields
p = Point(x=11, y=22)
p2 = p.__new__(Point, 10, 20)
# __getnewargs__, returns the namedtuple as a plain tuple
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y']) # define a type and its fields
p = Point(x=11, y=22)
t = p.__getnewargs__() # tuple, (11, 22)
Define Class
from collections import namedtuple
class Point(namedtuple('Point', ['x', 'y'])):
@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)
# p = Point._make([1, 2])
print(p)
Reference