代码之家  ›  专栏  ›  技术社区  ›  shadowtalker

如何提示变量是从另一个类继承的类?

  •  1
  • shadowtalker  · 技术社区  · 6 年前

    请考虑这个人为的代码片段:

    class Fooer():
        def __init__(self, *args, **kwargs):
            # do things
    
        def foo(self) -> int:
            # do more things
    
    def foo(fooer, *args, **kwargs) -> int:
        return x(*args, **kwargs).foo()
    

    我想暗示一下 fooer 论证 foo() 应该是 Fooer . 这不是 脚部 ,或者 脚部 自身或其子类。我能想到的是

    def foo(fooer: type, *args, **kwargs) -> int
    

    这还不够具体。

    我怎样才能更好地暗示这一点呢?

    2 回复  |  直到 6 年前
        1
  •  3
  •   chepner    6 年前

    来自PEP-484( The type of class objects ,解决方案是使用 Type[C] 指示的子类 C 在哪里 C 是由基类限定的类型变量。

    F = TypeVar('F', bound=Fooer)
    
    def foo(fooer: Type[F], *args,**kwargs) -> int:
        ...
    

    (公平地说,我不太明白使用 TypeVar 这里,如pep-484所示,而不是像@e.s.的答案那样使用类本身。)

        2
  •  2
  •   e.s.    6 年前

    那里有 Type 在里面 typing

    from typing import Type
    
    class A(object):
        def __init__(self, thing):
            self.thing = thing
    
    class B(A):
        pass
    
    def make_it(a_class: Type[A]):
        return a_class(3)
    
    make_it(B)  # type checks ok
    make_it(str)  # type checks complaining