【问题标题】:Incompatible types in assignment in inheritance - Mypy error继承中的赋值类型不兼容 - Mypy 错误
【发布时间】:2020-08-07 09:41:10
【问题描述】:

在我的项目中,我的 Mypy 因某些继承问题困扰着我,我找不到为什么在某些情况下它不会抱怨错误的原因:

note: In class "Cat":
Incompatible types in assignment (expression has type "Dict[str, Any]", base class "Animal" defined the type as "None")

而不是Dog,代码示例:

class Animal:
  attributes = None

  def __init__(self):
    if attributes is None:
      raise NotImplementedExcepton


class Cat(Animal):
  attributes = {
    'fur': 'black',
    'sound': 'meow',
  }

class Dog(Animal):
  attributes = {
    'fur': 'brown',
    'sound': 'woof',
  }

【问题讨论】:

  • "在某些情况下它不会抱怨" 在哪些情况下它不会抱怨?这些案例真的可取吗?为什么你首先分配attributes = None,而不是仅仅注释为例如attributes: Dict[str, Any]?
  • 我会编辑,但基本上看起来完全一样...
  • 我如何注释?

标签: python python-3.x mypy


【解决方案1】:

attributes 可以是None,如Animal 所示,因此您将其定义为Optional。然后,您还可以定义attributes 的类型。

from typing import Dict, Optional


class Animal:
    attributes: Optional[Dict[str, str]] = None

    def __init__(self):
        if self.attributes is None:
            raise Exception


class Cat(Animal):
    attributes = {
        'fur': 'black',
        'sound': 'meow',
    }

这不会引发任何 mypy 错误。

【讨论】:

    猜你喜欢
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2022-06-14
    • 2021-10-18
    • 2013-05-15
    • 1970-01-01
    相关资源
    最近更新 更多