考虑以下代码片段:
from collections import namedtuple
point = namedtuple("Point", ("x:int", "y:int"))
上面的代码只是为了演示我想要实现的内容。
我想使用类型提示创建 namedtuple
。
你知道任何优雅的方法来达到预期的结果吗?
考虑以下代码片段:
from collections import namedtuple
point = namedtuple("Point", ("x:int", "y:int"))
上面的代码只是为了演示我想要实现的内容。
我想使用类型提示创建 namedtuple
。
你知道任何优雅的方法来达到预期的结果吗?
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int = 1 # Set default value
Point(3) # -> Point(x=3, y=1)
dataclasses
。from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int = 1 # Set default value
Point(3) # -> Point(x=3, y=1)
frozen
标志,可以接近元组的行为。这只是需要注意的一点。 - shao.lotyping.NamedTuple
。namedtuple 的 类型化版本。
>>> import typing
>>> Point = typing.NamedTuple("Point", [('x', int), ('y', int)])
这仅在Python 3.5及以上版本中存在。
GeoPoint = NamedTuple('GeoPoint', [('longitude', float), ('latitude', float)])
,然后我尝试使用 geo = GeoPoint(**data)
,其中 data 是包含所需键和值为 decimal.Decimal
的字典,并且没有转换为浮点数发生;(没有 TypeError :( :( 那么这个 typing.NamedTuple
是如何工作的呢?请参见 https://gist.github.com/andilabs/15002176b2bda786b9037077fa06cc71。 - andilabsPoint = typing.NamedTuple("Point", x=int, y=int)
,这样会更加简洁明了。 - Marked as Duplicate公正起见,typing
中的NamedTuple
:
>>> from typing import NamedTuple
>>> class Point(NamedTuple):
... x: int
... y: int = 1 # Set default value
...
>>> Point(3)
Point(x=3, y=1)
等同于经典的namedtuple
:
>>> from collections import namedtuple
>>> p = namedtuple('Point', 'x,y', defaults=(1, ))
>>> p.__annotations__ = {'x': int, 'y': int}
>>> p(3)
Point(x=3, y=1)
def _make_nmtuple(name, types, module, defaults = ()):
fields = [n for n, t in types]
types = {n: _type_check(t, f"field {n} annotation must be a type")
for n, t in types}
nm_tpl = collections.namedtuple(name, fields,
defaults=defaults, module=module)
nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = types
return nm_tpl
NamedTuple
比这要复杂一些,它是一个在运行时实际执行某些操作的函数。 - chepnernamedtuple
的__annotations__
属性中,使用构造函数collections.namedtuple
。我将该代码添加到答案中以便更好地理解。 - mrvol