【问题标题】:is it possible to have 2 type hints for 1 parameter in Python? [duplicate]Python中的1个参数可以有2个类型提示吗? [复制]
【发布时间】:2020-05-20 01:55:36
【问题描述】:

所以这里我对容器类有一些定义:

class Box:
    def __init__(self, x1: int) -> None:

        self._x1 = x1

    @property
    def x1(self) -> int:
        return self._x1

然后在我的第二个函数中,我将传入这个 Box 对象

class Foo:
    def __init__(self, bar_1: Box) -> None

那么现在,在某些情况下,bar_1 也可以是 None...如果我将 none 传递给类 Foo,则会出现错误:

"Foo" has incompatible type "None"; expected "Box"

那么我怎么能绕过这个呢? python是否允许同时进行2种类型提示?

class Foo:
    def __init__(self, bar_1: Box or None) -> None

我需要帮助!

【问题讨论】:

标签: python type-hinting


【解决方案1】:

可选参数的类型提示应该是Optional:

from typing import Optional

def foo(bar: Optional[Box]): ...

这只是Union[Box, None] 的简写。更一般地说,Union 允许“多种类型提示”。

【讨论】:

    猜你喜欢
    • 2011-04-19
    • 2016-10-13
    • 2017-10-05
    • 1970-01-01
    • 2016-03-20
    • 2017-03-31
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    相关资源
    最近更新 更多