In [1]:
# https://docs.python.jp/3/library/collections.html#collections.namedtuple
In [2]:
from collections import namedtuple
In [3]:
Point = namedtuple('Point', ['x', 'y'])
In [4]:
print(Point)
In [5]:
p1 = Point(1, 2)
print(p1)
print(type(p1))
In [6]:
print(p1.x, p1.y)
print(p1[0], p1[1])
In [7]:
p_new = p1._replace(x=10)
print(p1)
print(p_new)
In [8]:
p_d = p1._asdict()
print(p_d)
print(type(p_d))
In [9]:
print(Point._fields)
In [10]:
Point_3D = namedtuple('Point_3d', Point._fields + ('z', ))
In [11]:
print(Point_3D)
In [12]:
p_3d = Point_3D(1, 2, 3)
print(p_3d)
print(type(p_3d))
In [13]:
p2 = Point(3, 4)
print(p2)
In [14]:
p = p1 + p2
print(p)
print(type(p))
In [15]:
class Point_a(namedtuple('Point_a', ['x', 'y'])):
def __add__(self, other):
return Point_a(self.x + other.x, self.y + other.y)
In [16]:
p1_a = Point_a(1, 2)
p2_a = Point_a(3, 4)
print(p1_a)
print(p2_a)
In [17]:
p_a = p1_a + p2_a
print(p_a)