有没有办法使用类作为Python内置数字类型的类型提示?

问题描述 投票:0回答:1

我想创建一个类,可以用作任何 python 内置数字类型的类型提示,例如 int、float、complex 或继承自 number.Number 的类

我想要这样的东西:

from fractions import Fraction


class AnyNumber(<whatever here>):
    ...


def foo(number: AnyNumber):
    ...


foo(1)  # Valid
foo(1.0)  # Valid
foo(1j)  # Valid
foo(Fraction())  # Also valid

我该怎么做?

我也尝试过使用numbers.Number作为类型提示,但我的Pylance和mypy说类似“int与Number不兼容”。

还有另一种方法可以在不使用

Union
的情况下做到这一点吗?

python python-3.x types numbers type-hinting
1个回答
0
投票

您可以使用协议

typing.SupportsComplex
来代替:

from typing import SupportsComplex
from fractions import Fraction

def foo(number: SupportsComplex):
    pass

foo(1)  # Valid
foo(1.0)  # Valid
foo(1j)  # Valid
foo(Fraction())  # Also valid

演示: https://mypy-play.net/?mypy=latest&python=3.11&gist=e327d5b393677e8b97b125d3184d74a6

© www.soinside.com 2019 - 2024. All rights reserved.