【问题标题】:Override Python property annotation覆盖 Python 属性注释
【发布时间】:2020-12-07 15:20:16
【问题描述】:

假设我有一个类似的基类:

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

然后,我定义了一个从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?

【问题讨论】:

  • 我认为你做不到。不过,我会注意到,关于您的评论“这是错误的:x 不是类级别的属性”:简单地在类级别进行注释实际上被认为是实例属性的注释。见here
  • 确实,您的信息回答了我的问题:将x(在BaseThingRationalizedThing 中)的注释移到类范围内。

标签: python inheritance annotations


【解决方案1】:

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

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

class RationalizedThing(BaseThing):
    x: Rational

【讨论】:

    猜你喜欢
    • 2011-12-25
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    相关资源
    最近更新 更多