简体   繁体   中英

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. anything_object can be A class or 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). You will have to import Union from standard library typing .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM