Code: Select all
def map_type(input):
if isinstance(input, int):
return MyEnum(input)
elif isinstance(input, str):
return MyCustomClass(str)
Code: Select all
def map_type(input: Union[int, str]) -> Union[MyEnum, MyCustomClass]: ...
Code: Select all
myvar = map_type('foobar')
print(myvar.property_of_my_custom_class)
Code: Select all
from typing import Union
from enum import Enum
class MyEnum(Enum):
VALUE_1 = 1
VALUE_2 = 2
class MyCustomClass:
def __init__(self, value: str) -> None:
self.value = value
@property
def myproperty(self) -> str:
return 2 * self.value
def map_type(value: Union[int, str]) -> Union[MyEnum, MyCustomClass]:
if isinstance(value, int):
return MyEnum(value)
elif isinstance(value, str):
return MyCustomClass(value)
raise TypeError('Invalid input type')
myvar1 = map_type(1)
print(myvar1.value, myvar1.name)
myvar2 = map_type('foobar')
print(myvar2.myproperty)
Ich habe auch darüber nachgedacht, mit Klassen und Polymorphismus zu arbeiten, aber wie würde ich dann die obersten Klassenmethoden mit Typhinweisen versehen? Weil ihr Ausgabetyp vom konkreten Instanztyp abhängen würde.
Mobile version