繁体   English   中英

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

[英]How to hint that a variable is a class inheriting from another class?

考虑以下人为设计的代码段:

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()

我想暗示foo()fooer参数应该是Fooer的子类。 它不是Fooer的实例, Fooer Fooer本身或其子类。 我能想到的最好的是

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

还不够具体。

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

从PEP-484( 类对象的类型 )中,解决方案是使用Type[C]指示C子类,其中C是由基类限制的类型var。

F = TypeVar('F', bound=Fooer)

def foo(fooer: Type[F], *args,**kwargs) -> int:
    ...

(说句公道话,我在PEP-484指示的TypeVar的答案中使用类本身之间并没有什么区别。)

还有一Typetyping

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM