在 Python 中模仿类型的最佳方法是什么?
如何在 Python 中定义 TestResult
Haskell 数据类型?
data TestResult
= TestResult {name :: String,
feature :: String,
passed :: Bool,
errorMessage :: String}
我试过了,但看起来有点傻。还有其他方法可以处理这种行为吗?
class TestResult:
def __init__(self, name, feature, passed, errorMessage):
self.name = name
self.feature = feature
self.passed = passed
self.errorMessage = errorMessage
我不是在寻找一些多余的类型,而是在寻找像“类型构造函数”这样的魔法组合,将一些数据 stub 组合成一个逻辑上单一的东西。
最佳答案
对于不可变数据,您可以使用 collections.namedtuple
:
>>> from collections import namedtuple
>>> TestResult = namedtuple("TestResult", "name feature passed errorMessage")
>>> TestResult("a", "b", True, "c")
TestResult(name='a', feature='b', passed=True, errorMessage='c')
关于python - python中的类型模仿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12440015/