有没有等同于Scala的Case类的Python?比如自动生成赋值给字段的构造函数,而不需要写出样板。
发布于 2018-07-15 02:41:14
当前的现代方法(从Python3.7开始)是使用data class。例如,Scala case class Point(x: Int, y: Int)
变成:
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: int
y: int
frozen=True
部分是可选的;您可以省略它以获得可变的数据类。为了与Scala的case类保持一致,我将其包含在内。
在Python3.7之前,有collections.namedtuple
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
命名元组是不可变的,因为它们是元组。如果你想添加方法,你可以扩展namedtuple:
class Point(namedtuple('Point', ['x', 'y'])):
def foo():
pass
https://stackoverflow.com/questions/51342228
复制相似问题