python - 如何在 Python 中定义代数数据类型?

标签 python algebraic-data-types

如何在 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/

相关文章:

python - 使用 matplotlib 基于类别的多色条

scala - 定义 ADT 时案例对象 T 和案例类 T() 之间的差异?

haskell - 代数数据类型的递归自下而上遍历

python - 打印一个奇特的字符串并在打印后更新它以模拟 GUI

python - 有没有办法检查我的代码的哪一部分使文件句柄处于打开状态

python - 抓取酒店评论的隐藏文本

python - 通过 python 和 cmd 查找 ip 地址之间的区别

从外部类继承的C++嵌套类;不允许不完整的类型

c# - 结构元组的性能

haskell - GADT : Difference between 'Algebraic' and 'Abstract' ?