新更新:
在 Python 3.6+ 中,您可以使用新的类型语法并创建 typing.NamedTuple
。新语法支持所有常见的 Python 类创建功能(文档字符串、多重继承、默认参数、方法等),从3.6.1版本开始可用。
import typing
class Pokemon(MyMixin, typing.NamedTuple):
"""
Attributes
----------
name : str
What do you call your Pokemon?
type : str
grass, rock, electric, etc.
level : int
Experience level [0, 100]
"""
name: str
type: str
level: int = 0
def method(self):
这个版本创建的类对象与原始的
collections.namedtuple
大多是等效的,
除了一些细节。您也可以使用与旧命名元组相同的语法:
Pokemon = typing.NamedTuple('Pokemon', [('name', str), ('type', str), ('level', int)])
原始答案
简短回答:不行,除非你使用的是Python < 3.5
P3文档似乎很清楚地暗示了,除非您需要添加计算字段(即描述符),否则子类化namedtuple
不被认为是规范的方法。这是因为您可以直接更新docstrings(它们现在从3.5开始可写!)。
子类化对于添加新的存储字段没有用。相反,只需从_fields
属性创建一个新的命名元组类型...
Docstrings可以通过直接分配给__doc__
字段来自定义...
更新:
现在,在最新版本的Python中,还有另外几种轻量级数据类的可能性。
其中之一是types.SimpleNamespace
(Python 3.3及更高版本)。它的结构不像namedtuple
那样结构化,但并不总是必要的。
需要注意的一件事是:默认情况下,要在实例化类时明确指定字段名称。不过,可以通过调用super().__init__
来轻松解决这个问题:
from types import SimpleNamespace
class Pokemon(SimpleNamespace):
"""
Attributes
----------
name : str
What do you call your Pokemon?
type : str
grass, rock, electric, etc.
level : int
Experience level [0, 100]
"""
__slots__ = ("name", "type", "level")
def __init__(self, name, type, level):
super().__init__(name=name, type=type, level=level)
另一个有趣的选择-Python 3.7已经提供了此功能-是dataclasses.dataclass
(还请参阅PEP 557):
from dataclasses import dataclass
@dataclass
class Pokemon:
__slots__ = ("name", "type", "level")
name: str
type: str
level: int = 0
请注意,这两个建议默认情况下都是可变的,并且不需要
__slots__
。
NamedTuple
和 dataclasses。 - pylang