如何在VS Code中告知Pylance/Pylint函数参数为自定义Python类?
解决Pylance/Pylint无法识别函数参数类型的问题
要让Pylance和Pylint识别函数参数的具体类类型,从而关联类方法的引用,最直接的方式是给函数参数添加类型注解或类型提示注释,以下是具体实现:
方法一:使用PEP 484类型注解
Python 3.5+支持直接在函数参数后标注所属类,这是官方推荐的类型提示方式:
class AlphaClass: def say_goodnight(self): print("Goodnight Kevin") # 给spam参数标注类型为AlphaClass def make_it_say_goodnight(spam: AlphaClass): print("Say Goodnight Kevin!") spam.say_goodnight() macaulay = AlphaClass() make_it_say_goodnight(macaulay)
添加注解后,Pylance和Pylint就能识别spam是AlphaClass的实例,此时查找AlphaClass.say_goodnight的所有引用时,会包含make_it_say_goodnight里的调用。
方法二:使用类型提示注释(兼容旧Python版本)
如果代码需要兼容Python 3.5之前的版本,可以在参数后添加注释指定类型:
class AlphaClass: def say_goodnight(self): print("Goodnight Kevin") def make_it_say_goodnight(spam): # type: AlphaClass print("Say Goodnight Kevin!") spam.say_goodnight() macaulay = AlphaClass() make_it_say_goodnight(macaulay)
这种方式同样能让静态分析工具识别参数类型,实现类方法引用的关联。
内容的提问来源于stack exchange,提问作者Helos35
相关产品推荐
相关产品推荐

