如何访问父类的__annotations __?

问题描述

是否可以访问父类的键入__ 注释 __?

在上面的示例中,类Student继承自类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

解决方法

self.__annotations__在没有名为__annotations__的实例属性的情况下等效于type(self).__annotations__。由于定义了Student.__annotations__,因此没有理由寻找Person.__annotations__。您需要检查MRO中的每个班级。最简单的方法是在某个基类中定义单个类方法(或使其成为与任何单个类都不关联的外部函数)。

class Person:
    name: str
    address: str

    @classmethod
    def get_annotations(cls):
        d = {}
        for c in cls.mro():
            try:
                d.update(**c.__annotations__)
            except AttributeError:
                # object,at least,has no __annotations__ attribute.
                pass
        return d

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


class Student(Person):
    year: int

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...