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

2024-05-17 03:42:44 发布

您现在位置:Python中文网/ 问答频道 /正文

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

#!/usr/bin/env python3

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

print(B.__annotations__)

输出:

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

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


Tags: envbinusr子类python3classintannotations
1条回答
网友
1楼 · 发布于 2024-05-17 03:42:44

想法:

#!/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()))

输出:

[('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__)

输出:

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

相关问题 更多 >