我有一个方法可以根据我传入的类返回动态类型:
def foo(cls):
return cls()
如何设置此功能的输入?
最佳答案
看完这篇文章https://blog.yuo.be/2016/05/08/python-3-5-getting-to-grips-with-type-hints/ ,我自己找到了解决方案:
from typing import TypeVar, Type
class A:
def a(self):
return 'a'
class B(A):
def b(self):
return 'b'
T = TypeVar('T')
def foo(a: T) -> T:
return a()
这个模板适合我上面的问题,但实际上,我的需求有点不同,我需要做更多的工作。下面我包括我的问题和解决方案:
问题:我想像这样使用with
关键字:
with open_page(PageX) as page:
page.method_x() # method x is from PageX
解决方案
from typing import TypeVar, Type, Generic
T = TypeVar('T')
def open_page(cls: Type[T]):
class __F__(Generic[T]):
def __init__(self, cls: Type[T]):
self._cls = cls
def __enter__(self) -> T:
return self._cls()
def __exit__(self, exc_type, exc_val, exc_tb):
pass
return __F__(cls)
因此,当我使用 PyCharm 时,当我将 PageX
传递给 with open_page(PageX) as page 时,它能够建议
method_x
:
关于python-3.x - Python根据参数动态返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48225097/