Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.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_Types_Annotations - Fatal编程技术网

是否有内置方法从Python中的所有基类获取所有注释?

是否有内置方法从Python中的所有基类获取所有注释?,python,types,annotations,Python,Types,Annotations,我们内置了dir()函数来获取在基于类中定义的类或实例的所有可用属性 注释是否也有相同的内容?我想使用get\u annotations()函数,其工作原理如下: def get_annotations(cls: type): ... # ? class Base1: foo: float class Base2: bar: int class A(Base1, Base2): baz: str assert get_annotations(A) ==

我们内置了
dir()
函数来获取在基于类中定义的类或实例的所有可用属性

注释是否也有相同的内容?我想使用
get\u annotations()
函数,其工作原理如下:

def get_annotations(cls: type): ...  # ?


class Base1:
    foo: float


class Base2:
    bar: int


class A(Base1, Base2):
    baz: str


assert get_annotations(A) == {'foo': float, 'bar': int, 'baz': str}


这应该能奏效,对吧

def get_annotations(cls: type):
    all_ann = [c.__annotations__ for c in cls.mro()[:-1]]
    all_ann_dict = dict()
    for aa in all_ann[::-1]:
        all_ann_dict.update(**aa) 
return all_ann_dict

get_annotations(A)
# {'bar': int, 'foo': float, 'baz': str}
或它的一行程序版本:

get_annotations = lambda cls: {k:v for c in A.mro()[:-1][::-1] for k,v in c.__annotations__.items()}

get_annotations(A)
# {'bar': int, 'foo': float, 'baz': str}