覆盖 Python 属性 注释

Override Python property annotation

假设我有一个像这样的基础 class:

class BaseThing:
    def __init__(self, value):
        self.x: Number = value

然后,我定义了一个更特殊的 class,它继承自 BaseThing:它不处理任何 Number,但特别处理 Rational。我想覆盖 属性 的注释,但我找不到方法:

class RationalizedThing(BaseThing):
    x: Rational  # This is wrong: x is not a class-level property

class RationalizedThing(BaseThing):
    def __init__(self, value: Rational):
        super().__init__(value)
        self.x: Rational  # Does not change anything in my linter's point of view.  Should it?

正如 Carcigenicate 和 this answer 所说,“假定 class 范围内的注释是指实例属性,而不是 class 属性”。所以那个是有效的:

class BaseThing:
    x: Number
    def __init__(self, value):
        self.x = value

class RationalizedThing(BaseThing):
    x: Rational