Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python方法参数注释类_Python_Annotations - Fatal编程技术网

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!')