Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.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_Python 3.x_Python Typing - Fatal编程技术网

Python 如何访问父类的注释?

Python 如何访问父类的注释?,python,python-3.x,python-typing,Python,Python 3.x,Python Typing,有没有办法访问父类的键入注释 在上面的示例中,类Student继承自类Person,但它不包含来自Person类的键入注释 班级人员: 姓名:str 地址:str 定义初始化(自): 打印(自我注释) 班级学生(人): 年份:整数 person=person() #{'name':,'address':} 学生=学生() #{'year':} #在这里,我期待着名字和地址的道具 self.\uuuuu annotations\uuuuu在缺少名为\uuuuuu annotations\uuuuu

有没有办法访问父类的键入注释

在上面的示例中,类
Student
继承自类
Person
,但它不包含来自
Person
类的键入注释

班级人员:
姓名:str
地址:str
定义初始化(自):
打印(自我注释)
班级学生(人):
年份:整数
person=person()
#{'name':,'address':}
学生=学生()
#{'year':}
#在这里,我期待着名字和地址的道具

self.\uuuuu annotations\uuuuu
在缺少名为
\uuuuuu annotations\uuuuu
的实例属性的情况下,等同于
类型(self)。\uuuuu annotations\uuuuuu
。由于定义了
Student.\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu注释
,因此没有理由查找
Person.\uuuuuuuuuuuuuuuuuuuuuuuuuuuu。您需要检查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