我有一个类,它有一个创建类实例的方法。
class Bar:
@classmethod
def create(cls, foo: int):
return cls(foo)
def __init__(self, foo: int) -> None:
pass
Run Code Online (Sandbox Code Playgroud)
当我针对它运行 mypy 时,它说 mypytest.py:4: error: Too many arguments for "Bar"
这对我来说似乎是一个错误,因为这很好用
class Bar:
@classmethod
def create(cls, foo):
return cls(foo)
def __init__(self, foo: int) -> None:
pass
Run Code Online (Sandbox Code Playgroud)
我不明白为什么定义参数类型的类方法会破坏实例的创建。我错过了什么吗?
答案很简单,把__init__方法放在第一位。例如这工作正常:
class Bar:
def __init__(self, foo: int) -> None:
pass
@classmethod
def create(cls, foo: int):
return cls(foo)
Run Code Online (Sandbox Code Playgroud)
由于某些技术原因,如果__init__(或__new__) 不是类定义中的第一个方法,则 mypy 当前在某些极端情况下的行为会出乎意料。我想我已经看到了类似的问题,但是在 mypy tracker 上找不到问题。
| 归档时间: |
|
| 查看次数: |
2813 次 |
| 最近记录: |