我试图使用功能注释,希望我的编辑能够更好地进行重构。然而,我遇到了以下问题:
我有一个抽象的基类算法。
class Algorithm(metaclass=ABCMeta):
def __init__(self):
self.foo = 'bar'
我还有一个使用Algorithm
子类实例的函数def get_foo(foo_algorithm):
return foo_algoritm.foo
输入foo_algorithm可以是Algorithm的任何子类的实例。我如何明智地注释这个输入?我一直在找东西:
def get_foo(foo_algorithm: subclassof(Algorithm)):
return foo_algoritm.foo
但我无法找到正确的方法。
答案 0 :(得分:4)
直接使用def get_foo(foo_algorithm: Algorithm):
return foo_algoritm.foo
:
isinstance(foo_algorithm, Algorithm)
并且自动接受子类的任何实例(Type[Algorithm]
必须为true,这适用于基类的所有子类。)
如果您只接受类,请使用def get_foo(foo_algorithm: Type[Algorithm]):
return foo_algoritm().foo
作为类型提示:
Type[C]
请参阅PEP 484的The type of class objects section - 类型提示:
有时你想谈论类对象,特别是从给定类继承的类对象。这可以拼写为
C
,其中C
是一个类。澄清:虽然C
(当用作注释时)引用类Type[C]
的实例,但C
引用.foo
的子类。
这里我调用了类对象,因为根据你的代码示例,Algorithm
是一个实例属性;从Nsurlsesiondownloadtask
派生的类本身不具有这样的属性。