问题描述
假设我有一个函数,它将根据字符串输入参数返回一个类,如下所示:
Say I have a function that will return a class based on a string input parameter, like so:
def foo(bar):
if bar == 'baz':
return Baz()
else:
return Buz()
在这种情况下,Baz
和 Buz
都是 Biz
的子类,但每个都有许多不同的函数,因此声明返回type 作为超类并不是特别有用.假设我不在乎我的 .pyi
文件是否可怕,有什么方法可以让我声明为给定输入返回的子类?
In this case, both Baz
and Buz
are subclasses of Biz
, but each has a number of distinct functions, so declaring the return type as the superclass is not particularly useful. Assuming I don't care if my .pyi
file is hideous, is there any way for me to declare what subclass is returned for a given input?
推荐答案
我认为你不能那么具体,你可以做的是声明某些东西返回两种不同的类型,如下所示:
I don't think you can quite that specifically, what you can do though is declare that something returns two different types like so:
from typing import Union
class Bar:
pass
class Baz:
pass
def foo(garply : str) -> Union[Bar, Baz]:
pass
看看这里的文档:https://www.python.org/dev/peps/pep-0484/#union-types
这里有一个合理的简短概述:http://blog.jetbrains.com/pycharm/2015/11/python-3-5-type-hinting-in-pycharm-5/
And a reasonable short overview here:http://blog.jetbrains.com/pycharm/2015/11/python-3-5-type-hinting-in-pycharm-5/
您最好考虑如何避免这种有问题的设计,而不是如何使用类型提示完美地记录它.
You might be better off thinking how to avoid this questionable design rather than how to perfectly document it with type hints.
这篇关于使用 PEP 484 的动态返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!