python/mypy:如何使用实现为 属性 和属性的值来声明 ABC
python/mypy: how to declare ABC using value implemented both as property and attribute
我有一个抽象基础class,它使用一个值,该值在不同的具体 classes 中的实现可以是属性或 属性:
from abc import ABC, abstractmethod
class Base(ABC):
n: int
def foo(self):
...
a = ... + self.n
@abstractmethod
def bar(self):
...
class X(Base):
def __init__(self, n: int):
self.n = n
def bar(self):
...
class Y(Base):
@property
def n(self) -> int:
...
def bar(self):
...
以上代码(大纲,适当填写)在运行时有效,但 mypy 抱怨 Y
中的 属性:
error: Signature of "n" incompatible with supertype "Base"
但是,由于 foo
,我无法删除 n: int
,而且我也无法放入摘要 属性,因为这会破坏 X
.我应该如何声明基数 class 让 mypy 满意?
Y
不能比 Base
更灵活并且是一个子类,因此您可能需要将 n
抽象为 属性 Base
然后添加一个 setter 到 X
。它不漂亮,但它有效(我想,我还没有检查)
class X(Base):
def __init__(self, n: int):
self._n = n
@property
def n(self) -> int:
return self._n
@n.setter
def n(self, n: int) -> None:
self._n = n
...
我有一个抽象基础class,它使用一个值,该值在不同的具体 classes 中的实现可以是属性或 属性:
from abc import ABC, abstractmethod
class Base(ABC):
n: int
def foo(self):
...
a = ... + self.n
@abstractmethod
def bar(self):
...
class X(Base):
def __init__(self, n: int):
self.n = n
def bar(self):
...
class Y(Base):
@property
def n(self) -> int:
...
def bar(self):
...
以上代码(大纲,适当填写)在运行时有效,但 mypy 抱怨 Y
中的 属性:
error: Signature of "n" incompatible with supertype "Base"
但是,由于 foo
,我无法删除 n: int
,而且我也无法放入摘要 属性,因为这会破坏 X
.我应该如何声明基数 class 让 mypy 满意?
Y
不能比 Base
更灵活并且是一个子类,因此您可能需要将 n
抽象为 属性 Base
然后添加一个 setter 到 X
。它不漂亮,但它有效(我想,我还没有检查)
class X(Base):
def __init__(self, n: int):
self._n = n
@property
def n(self) -> int:
return self._n
@n.setter
def n(self, n: int) -> None:
self._n = n
...