如何在 Python(2 或 3)中定义代数数据类型?
最佳答案
typing
模块提供了 Union
,它与 C 不同,是 sum 类型。您需要使用 mypy 进行静态类型检查,并且明显缺乏模式匹配,但结合元组(产品类型),这是两种常见的代数类型。
from dataclasses import dataclass
from typing import Union
@dataclass
class Point:
x: float
y: float
@dataclass
class Circle:
x: float
y: float
r: float
@dataclass
class Rectangle:
x: float
y: float
w: float
h: float
Shape = Union[Point, Circle, Rectangle]
def print_shape(shape: Shape):
if isinstance(shape, Point):
print(f"Point {shape.x} {shape.y}")
elif isinstance(shape, Circle):
print(f"Circle {shape.x} {shape.y} {shape.r}")
elif isinstance(shape, Rectangle):
print(f"Rectangle {shape.x} {shape.y} {shape.w} {shape.h}")
print_shape(Point(1, 2))
print_shape(Circle(3, 5, 7))
print_shape(Rectangle(11, 13, 17, 19))
# print_shape(4) # mypy type error
关于python - 如何在 Python 中定义代数数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16258553/