繁体   English   中英

为什么 Python 子类不继承其父类的注解?

[英]Why a Python subclass does not inherit its parent class's annotations?

Python 子类显然不继承其父类的注释:

#!/usr/bin/env python3

class A:
    valA: int
    
class B(A):
    valB: str

print(B.__annotations__)

Output:

{'valB': <class 'str'>}

这是为什么? 我怎样才能做到这一点?

主意:

#!/usr/bin/env python3

def updateAnnotations(annotations, bases):
    for base in bases:
        annotations.update(getattr(base, '__annotations__', dict()))

class A:
    valA: int
    
class B:
    valB: int
    
class C(A, B):
    valC: int
    
    updateAnnotations(__annotations__, [A, B])

print(sorted(C.__annotations__.items()))

Output:

[('valA', <class 'int'>), ('valB', <class 'int'>), ('valC', <class 'int'>)]

使用装饰器:

def update_annotations(cls: typing.Type) -> typing.Type:
    annotations = getattr(cls, '__annotations__', None)
    if annotations == None:
        cls.__annotations__ = dict()
        annotations = cls.__annotations__

    for clsType in [cls] + list(cls.__bases__):
        annotations.update(getattr(clsType, '__annotations__', dict()))

    return cls

class A:
    valA: int

class B:
    valA: str
    valB: int

@update_annotations    
class C(A, B):
    valC: int
    
    def __init__(self):
        self.valA = 'asd'
        self.valB = 30
        self.valC = 40

print(C.__annotations__)

Output:

{'valC': <class 'int'>, 'valA': <class 'str'>, 'valB': <class 'int'>}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM