如何访问父类的 __annotations__ ?

Ale*_*aro 3 python python-3.x python-typing

有什么办法可以访问父类的类型__注解__吗?

在上面的示例中,该类Student继承自 class Person,但它不包含该类的类型注释Person

class Person:
    name: str
    address: str

    def __init__(self):
        print(self.__annotations__)


class Student(Person):
    year: int


person = Person()
# {'name': <class 'str'>, 'address': <class 'str'>}

student = Student()
# {'year': <class 'int'>}
# HERE I would expect the name and the address props
Run Code Online (Sandbox Code Playgroud)

Jus*_*her 7

当谷歌搜索将我带到这里时,这就是我希望看到的答案。

from collections import ChainMap

def all_annotations(cls) -> ChainMap:
    """Returns a dictionary-like ChainMap that includes annotations for all 
       attributes defined in cls or inherited from superclasses."""
    return ChainMap(*(c.__annotations__ for c in cls.__mro__ if '__annotations__' in c.__dict__) )
Run Code Online (Sandbox Code Playgroud)

与 @chepner 的方法不同,这可以正确处理多个超类为同一属性名称提供不同注释的情况(这通常是不可取的,但可以很好,例如,当子类提供具有更具体注释的属性时)。@chepner 的方法将优先考虑方法解析顺序 (MRO) 中最后出现的注释,而 Python 的类继承通常优先考虑按该顺序最先出现的类。(如果您确实想使用 @chepner 的方法,您可能最好以MRO 的相反方式更新注释,注意不要意外丢失此类中定义的任何注释。)