为什么在创建 namedtuple 子类时传递对象的名称?
Why pass the name of object in creating namedtuple subclass?
我知道这是创建 namedtuple
p:
的格式
Point = namedtuple('Point', ['x', 'y'])
p = Point(11, y=22)
为什么我们传递 对象的名称 ,这里 Point
作为 namedtuple
的参数之一。如果Point
这里是元组的新子类,带有命名字段,它的调用者不会自动作为第一个参数传递吗?为什么 namedtuple
不能 called/initiated 类似于 numpy.array
import numpy
l = numpy.array([1, 2, 3]) # so simple
使用typing.NamedTuple
避免重名声明。
from typing import NamedTuple
class Point(NamedTuple):
x: float
y: float
collections.namedtuple
不是类型,是类型工厂;
每个 namedtuple
构成一个单独的类型。例如,namedtuple('Point', ['x', 'y'])
和 namedtuple('Point', ['x', 'y', 'z'])
是不同的类型。 Python 默认为 nominal typing, and relies on the type name to report and store types。因此,像 namedtuple('Point', ['x', 'y'])
这样的类型应该知道它的名字,因此需要传入它。
相比之下,numpy.array
已经是一个类型,具有已知名称 array
。 numpy.array([1, 2, 3])
创建 array
的 实例 ,就像 Point(1, 2)
创建 namedtuple 实例 Point
.
我知道这是创建 namedtuple
p:
Point = namedtuple('Point', ['x', 'y'])
p = Point(11, y=22)
为什么我们传递 对象的名称 ,这里 Point
作为 namedtuple
的参数之一。如果Point
这里是元组的新子类,带有命名字段,它的调用者不会自动作为第一个参数传递吗?为什么 namedtuple
不能 called/initiated 类似于 numpy.array
import numpy
l = numpy.array([1, 2, 3]) # so simple
使用typing.NamedTuple
避免重名声明。
from typing import NamedTuple
class Point(NamedTuple):
x: float
y: float
collections.namedtuple
不是类型,是类型工厂;
每个 namedtuple
构成一个单独的类型。例如,namedtuple('Point', ['x', 'y'])
和 namedtuple('Point', ['x', 'y', 'z'])
是不同的类型。 Python 默认为 nominal typing, and relies on the type name to report and store types。因此,像 namedtuple('Point', ['x', 'y'])
这样的类型应该知道它的名字,因此需要传入它。
相比之下,numpy.array
已经是一个类型,具有已知名称 array
。 numpy.array([1, 2, 3])
创建 array
的 实例 ,就像 Point(1, 2)
创建 namedtuple 实例 Point
.