Python类型提示:自定义数据类型

发布于 2025-01-23 14:22:43 字数 567 浏览 0 评论 0 原文

假设,我想拥有一个我称为 size 的自定义类型。 从根本上讲,这种类型不过是INT。

但是,我想具有以下行为:

some_size: Size = 42
not_a_size: int = 12

>>> isinstance(some_size, int)
True

>>> isinstance(some_size, Size)
True

>>> isinstance(not_a_size, int)
True

>>> isinstance(not_a_size, Size)
False

定义类型别名: size = int 是可能的,但是 isInstance(not_a_size,size,size)会返回 true 。 我还探索了 typevar size = typevar('size',bound = int)),但不是为此做出的。

Let say, I want to have a custom type that I call Size.
Fundamentally, this type is nothing more than an int.

However, I would like to have the following behaviour:

some_size: Size = 42
not_a_size: int = 12

>>> isinstance(some_size, int)
True

>>> isinstance(some_size, Size)
True

>>> isinstance(not_a_size, int)
True

>>> isinstance(not_a_size, Size)
False

Defining a type alias: Size = int is possible, but isinstance(not_a_size, Size) would return True.
I also explored TypeVar (Size = TypeVar('Size', bound=int)) but it is not made for this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文