问题描述
是否可以访问父类的键入__ 注释 __?
在上面的示例中,类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