[英]How to write the type hint for an argument that can be of either class A or class B?
I want to put an object as the argument value of the function.我想将 object 作为 function 的参数值。
anything_object
can be A class or B class. anything_object
对象都可以是 A class 或 B class。
class A:
name: str
class B:
phone: int
class ObjectInfo
def __init__(self) -> None:
pass
def getObjectFieldName(self, anything_object: ?) -> list:
return dir(anything_object)
You can use Union
to specify multiple type hintings (for both, arguments and return type).您可以使用
Union
指定多种类型提示(对于两者,arguments 和返回类型)。 You will have to import Union
from standard library typing
.您必须从标准库
typing
中导入Union
。
from typing import Union
class A:
def __init__(self, name) -> None:
self.name = name
class B:
def __init__(self, name) -> None:
self.name = name
class ObjectInfo:
def __init__(self) -> None:
pass
def method(self, object:Union[A, B]=None) -> list:
return dir(object)
obj = ObjectInfo()
print(obj.method())
[External Links] [外部链接]
More on type hinting: https://docs.python.org/3/library/typing.html更多关于类型提示: https://docs.python.org/3/library/typing.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.