python方法参数注释类
由于尚未定义python方法参数注释类,python,annotations,Python,Annotations,由于尚未定义Foo,以下情况导致导入错误: class Foo: def __init__(self, rhs: Foo): pass 有没有办法注释rhs,表明它应该是Foo的另一个实例 不太可能。Python在定义C++类之前,没有任何方法可以声明它。 如果您只是想让人们看到rhs应该是Foo,那么您可以始终使用字符串文字: def __init__(self, rhs: 'Foo'): # or def __init__(self, rhs: "<class
Foo
,以下情况导致导入错误:
class Foo:
def __init__(self, rhs: Foo):
pass
有没有办法注释
rhs
,表明它应该是Foo
的另一个实例 不太可能。Python在定义C++类之前,没有任何方法可以声明它。
如果您只是想让人们看到rhs
应该是Foo
,那么您可以始终使用字符串文字:
def __init__(self, rhs: 'Foo'):
# or
def __init__(self, rhs: "<class '__main__.Foo'>"):
但我个人只会使用第一种解决方案。函数注释的主要目的是记录函数。因此,执行此操作的字符串文字满足注释的目的。为什么不签入初始值设定项:
if ( not isinstance(rhs, Foo)):
raise Exception('Not the right class!')
很不幸,但我必须给你这个。我尝试了基于字符串的注释,但出于几个原因,我并不喜欢它。我将在单独的答案中对此进行讨论,以防其他人发现这一点有用。
if ( not isinstance(rhs, Foo)):
raise Exception('Not the right class!')