我正在使用将字典作为输入但Pycharm显示警告的方法来构建类。
'''预期的类型为“ TestClass”,取而代之的是“ Dict [str,int]” ...(⌘F1)检查信息:此检查检测函数调用表达式中的类型错误。由于动态调度和鸭子输入,这在有限但有用的情况下是可能的。可以在文档字符串或Python 3函数注释中指定函数参数的类型'''
class TestClass:
def __getitem__(self, index):
return self[index]
def get_keys(self):
return list(self.keys())
dict_input = {'a':123, 'b':456}
TestClass.get_keys(dict_input)
所以我在这里得到警告:
TestClass.get_keys(dict_input)
此警告是什么意思,它的解决方法是什么?
[您编写的方法称为“实例方法”。
self
,接收者,应该是TestClass
的实例(否则,很多事情可能会出错,例如super
。]]
您可以将get_keys
定义为静态方法,或使用简单的函数(无需将其放在类中。)>
class TestClass: @staticmethod def get_keys(s): return list(s.keys())
您可能想阅读Python documentation about classes以获取更多详细信息。