我正在尝试__new__
在 Python 的元类中键入该方法,以便它使 mypy 满意。代码将是这样的(取自pep-3115 - “Python 3000 中的元类”并精简了一点):
from __future__ import annotations
from typing import Type
# The metaclass
class MetaClass(type):
# The metaclass invocation
def __new__(cls: Type[type], name: str, bases: tuple, classdict: dict) -> type:
result = type.__new__(cls, name, bases, classdict)
print('in __new__')
return result
class MyClass(metaclass=MetaClass):
pass
Run Code Online (Sandbox Code Playgroud)
有了这个,mypy 抱怨说,Incompatible return type for "__new__" (returns "type", but must return a subtype of "MetaClass")
,指着线def __new__
。
我也试过:
def __new__(cls: Type[MetaClass], name: str, bases: …
Run Code Online (Sandbox Code Playgroud)