我如何在 python中获得 scala 的密封 类的好处?也就是说,可以仅在定义它的模块中对类进行子类化。
注意不是这篇文章的欺骗。C#sealed
相当于 scala 的final
.
我可能想要的一个例子是定义一个数组类型,并在该类型中指定它的形状如下
from typing import final, TypeVar, Generic
from abc import ABC, abstractmethod
S = TypeVar('S', bound=Shape)
class Array(ABC, Generic[S]):
@abstractmethod
def shape(self) -> S:
pass
class Shape(ABC): # how to make this sealed, or similar?
pass
@final
class Shape1(Shape):
pass
@final
class Shape2(Shape):
pass
def fn(arr: Array[Shape2]):
# some calculation that requires it to be a rank-2 array
事实上,有人可以继承Shape
并制作自己的 rank 2 形状,fn
即使它是有效的,也不会被 接受(当然这样做不一定是个好主意,但用户可以做他们喜欢的事)。
其他示例正在制作适当的枚举。我知道没有模式匹配,但我想定义一个Either
类型并让某人创建第三个子类会令人困惑。