python - 如何修复类属性和非属性成员的继承覆盖之间的分配静态类型错误?
问题描述
假设我正在使用带有 @property 的 classproperty @staticmethod 的这种实现:
class classproperty(property):
def __get__(self, cls, owner):
return classmethod(self.fget).__get__(None, owner)()
- 当您仍想使用属性装饰器但没有 a 时,这对于无实例类(如 Java 接口)
self
很有用,只有 acls
您如何满足 linter 并强制转换类方法,以便当它们发生覆盖时,您不会收到类型 Callable[[Type], IntendedType] 不是 IntendedType 的 linter 错误?
这是一个例子:
Class A:
@classproperty
def foo(cls) -> str:
return 'bar'
class B(A):
foo = 'not bar'
当我在此代码上运行mypy时,出现以下错误:
error: Incompatible types in assignment (expression has type "str", base class "A" defined the type as "Callable[[A], str]") [assignment]
看起来处理这个问题的方法是:
Class A:
@classproperty
def foo(cls) -> str:
return 'bar'
foo = cast(str, foo)
但这只是感觉不对(也不起作用)。
有没有办法通过修改某些部分来达到相同的结果classproperty
?
除了在文件开头添加一些注释以完全忽略 linter 检查之外?(我不感兴趣,不是在文件的开头,也不是每个特定的行)
解决方案
推荐阅读
- javascript - 如何将路径到对象的极深道具映射到带有一些额外道具的新对象?
- java - 在方法中使用正则表达式输出
- android - 关于在 Flutter 中创建风味
- unity3d - 统一的 2D 布娃娃运动
- python-3.x - 使用 Python 将属性从 AWS Connect 传递到 Lambda
- vb.net - 在 RichTextBox 中获取实际的 SelectionStart 位置?
- node.js - 节点 - 将表与 Sequelize 关联
- arrays - 标记包含过滤器列表中单词的单元格
- json - 将两个相同文件的json文件合二为一
- java - 如何在 Android 10 中创建自定义目录“/storage/emulated/0/TestDir”?