Ashamed to say, I have been using python for a long time, and this is the first time I found such a good thing as namedtuple. Code first:
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
pt1 = Point(1.0, 5.0)
pt2 = Point(2.5, 1.5)
from math import sqrt
line_length = sqrt((pt1.x-pt2.x)**2 + (pt1.y-pt2.y)**2)
Isn't it fun? Point is like a class that has defined x and y properties. It can directly create instances, and all instances can access its properties in the form of .x and .y, which is much easier than defining classes directly:
class Point:
def __init__(self, x: float, y: float):
self.x = x
self.y = y
pt1 = Point(1.0, 5.0)
pt2 = Point(2.5, 1.5)
from math import sqrt
line_length = sqrt((pt1.x - pt2.x) ** 2 + (pt1.y - pt2.y) ** 2)
Obviously, it's also more readable than using a raw tuple:
pt1 = (1.0, 5.0)
pt2 = (2.5, 1.5)
from math import sqrt
# use index referencing
line_length = sqrt((pt1[0]-pt2[0])**2 + (pt1[1]-pt2[1])**2)
# use tuple unpacking
x1, y1 = pt1
There are only two members, and if there are more, the various numbers will confuse people.
So namedtuple is a shortcut for creating data classes based on tuple, allowing us to define data structures quickly and easily. Of course, it also has an obvious disadvantage: since the bottom layer is implemented with tuple, it is impossible to change (immutable), so pt1.x = 7
such as 061e150b94beb3 will obviously report an error.
If you want a mutable shortcut data class, you can use pyrecord:
from pyrecord import Record
Point = Record.create_type('Point', 'x', 'y')
pt1 = Point(1.0, 5.0)
pt2 = Point(2.5, 1.5)
from math import sqrt
line_length = sqrt((pt1.x - pt2.x) ** 2 + (pt1.y - pt2.y) ** 2)
pt1.x = 3.6
new_length = sqrt((pt1.x - pt2.x) ** 2 + (pt1.y - pt2.y) ** 2)
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。