1
我想使用类方法返回当前类的新实例,和我有尝试像下面的一些代码,但它引发NameError(“名称‘T’没有定义”)如何让python类型检查器知道它应该返回它的类的新实例?
把代码T = TypeVar('T', bound=A)
上class A
以上都不起作用。
有什么好主意来处理它?
import json
from typing import TypeVar
class A(dict):
def __init__(self, name):
super(dict, self).__init__()
self["name"] = name
@classmethod
def foo(cls: T, args: str)->T:
return json.loads(args)
T = TypeVar('T', bound=A)
class B(A):
pass
b = B(name='B')
# True
print(isinstance(b.foo(json.dumps(b)),B))
谢谢你很多。它可以工作,但我在pycharm上看不到任何提示。它看起来像这个IDE的一个bug,因为pycharm没有完全实现pep484标准[pycharm 2017.1.3]。 – FavorMylikes