Python 中是否有与 Scala 的 Case Class 等效的东西?就像自动生成分配给字段而无需编写样板的构造函数一样。
当前执行此操作的现代方法(从 Python 3.7 开始)是使用数据类 https://www.python.org/dev/peps/pep-0557。例如,斯卡拉case class Point(x: Int, y: Int)
变成:
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: int
y: int
The frozen=True
部分是可选的;您可以省略它以获得可变数据类。我将其包含在内是为了与 Scala 的案例类保持一致。
在Python 3.7之前,有collections.namedtuple https://docs.python.org/3/library/collections.html#collections.namedtuple:
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
命名元组是不可变的,因为它们是元组。如果你想添加方法,你可以扩展namedtuple:
class Point(namedtuple('Point', ['x', 'y'])):
def foo():
pass
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)