python - 是否有内置方法从 Python 的所有基类中获取所有 __annotations__?

标签 python types annotations

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

注解也一样吗?我想要 get_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}

关于python - 是否有内置方法从 Python 的所有基类中获取所有 __annotations__?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64309238/

相关文章:

regex - 关于正则表达式的证明

java - @MustOverride 注释?

python - 在python中使用默认消息引发内置异常

python - 当 python 函数比它们更快时,为什么我们使用 pyspark UDF? (注意。不用担心 Spark SQL 命令)

java - Sentence Splitter 测试文件

function - 不明白这个 haskell 代码中的内容

Python将列表作为参数传递

c# - 泛型类型参数和类型

java - Spring 3.2 中@MatrixVariable 注解的一些信息

java - 高效的 Java 注解