【问题标题】:Python return typing dynamically based on parameterPython根据参数动态返回类型
【发布时间】:2018-01-20 13:45:44
【问题描述】:

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

def foo(cls):
    return cls()

如何设置此功能的输入?

【问题讨论】:

    标签: python-3.x typing


    【解决方案1】:

    看完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

    【讨论】:

    • 很棒的解决方案,这非常适合我的用例
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    • 2017-11-22
    • 2018-04-30
    • 2020-12-26
    相关资源
    最近更新 更多