【问题标题】:How to declare instance variables in ABC which implementations could have different types如何在 ABC 中声明实例变量,哪些实现可以有不同的类型
【发布时间】:2022-01-23 17:04:45
【问题描述】:

我有一个ABC,它的所有实现类中都会有一个实例变量,比如说record。为了便于阅读,我想让读者知道 ABC 的实例应该有一个 record 实例变量。

但是,record 的类型在不同的实现类中有所不同。而且我想避免让我的ABC 指定record 可以使用的所有可能类型(例如ABC 中的record: DjangoModelA | DjangoModelB),因为这对我来说很不合适。

这是我当前代码的简单版本:

class Abstract(ABC):
    record: None

class SubA(Abstract):
    record: DjangoModelA

class SubB(Abstract):
    record: DjangoModelB

mypy 抱怨的:

error: Incompatible types in assignment (expression has type "DjangoModelA", base class "Abstract" defined the type as "None")
error: Incompatible types in assignment (expression has type "DjangoModelB", base class "Abstract" defined the type as "None")

我应该如何声明抽象基类才能让 mypy 和我满意?

【问题讨论】:

    标签: python abstract-class instance-variables mypy python-typing


    【解决方案1】:

    record 会一直是 django 模型吗?如果是这样,我想你可以试试:

    from django.db import models
    class Abstract(ABC)
        record: models.Model
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-17
      • 1970-01-01
      • 2014-10-02
      • 1970-01-01
      • 2011-08-15
      • 2012-02-28
      • 2018-04-05
      相关资源
      最近更新 更多