Python return 根据参数动态输入

Python return typing dynamically based on parameter

我有一个方法 returns 基于我传入的 class 的动态类型:

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