python-3.x - Python根据参数动态返回类型

标签 python-3.x typing

我有一个方法可以根据我传入的类返回动态类型:

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/

相关文章:

c++ - _r 后缀是什么意思?

javascript - Typeit.js 从数组中输入随机字符串

python - 在 Python 中计算目录中的一组扩展名(图像)

string - 将组件由符号分隔的字符串转换为嵌套的 python 字典

python - 如何使用小的单个图像并在整个窗口中重复它以使用 tkinter GUI 使其成为背景图像?

python - 如何注释 f(*params)?

dynamic - 在 C# 中获取动态类型的 ServiceStack.redis 客户端

python - 从林间空地创建 Gtk.ApplicationWindow

http - 当 python3 抛出 HTTPError 时,如何获取 http 正文

Python 3.5 键入 ABCMeta 未定义 '__getitem__'