Python 等价于 Scala 案例类 [英] Python equivalent of Scala case class
问题描述
是否有任何 Python 等价于 Scala 的 Case Class?就像自动生成分配给字段的构造函数一样,而无需写出样板.
Is there any Python equivalent of Scala's Case Class? Like automatically generating constructors that assign to fields without writing out boilerplate.
推荐答案
当前的现代方法(从 Python 3.7 开始)是使用 数据类.例如,Scala case class Point(x: Int, y: Int)
变为:
The current, modern way to do this (as of Python 3.7) is with a data class. For example, the Scala case class Point(x: Int, y: Int)
becomes:
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: int
y: int
frozen=True
部分是可选的;您可以省略它以获得可变数据类.我已经将它包含在 Scala 的 case 类中.
The frozen=True
part is optional; you can omit it to get a mutable data class. I've included it for parity with Scala's case class.
在 Python 3.7 之前,有 collections.namedtuple
:
Before Python 3.7, there's collections.namedtuple
:
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
命名元组是不可变的,因为它们是元组.如果要添加方法,可以扩展namedtuple:
Namedtuples are immutable, as they are tuples. If you want to add methods, you can extend the namedtuple:
class Point(namedtuple('Point', ['x', 'y'])):
def foo():
pass
这篇关于Python 等价于 Scala 案例类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!