如何暗示一个变量是 class 继承自另一个 class?
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
本身或其子类。我能想到的最好的是
def foo(fooer: type, *args, **kwargs) -> int
不够具体。
我怎样才能更好地暗示这一点?
来自 PEP-484 (The type of class objects),解决方案是使用 Type[C]
来表示 C
的子 class,其中 C
是由你的基 class.
限定的类型 var
F = TypeVar('F', bound=Fooer)
def foo(fooer: Type[F], *args,**kwargs) -> int:
...
(公平地说,我不太明白这里使用 TypeVar
与使用 class 本身(如 PEP-484 所示)之间的区别 @e.s.的回答。)
typing
中有一个Type
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
考虑这个人为设计的代码片段:
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
本身或其子类。我能想到的最好的是
def foo(fooer: type, *args, **kwargs) -> int
不够具体。
我怎样才能更好地暗示这一点?
来自 PEP-484 (The type of class objects),解决方案是使用 Type[C]
来表示 C
的子 class,其中 C
是由你的基 class.
F = TypeVar('F', bound=Fooer)
def foo(fooer: Type[F], *args,**kwargs) -> int:
...
(公平地说,我不太明白这里使用 TypeVar
与使用 class 本身(如 PEP-484 所示)之间的区别 @e.s.的回答。)
typing
Type
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