我最近将一个实例方法从其类定义中移出,并将其作为全局函数(例如:deco_function(,以便能够在不同的类中再次使用它。有关详细解释和错误再现,请参阅以下代码:
def deco_function(cls):
def inner_fct(self):
print('do something')
cls.deco_function = inner_fct
return cls
@deco_function
class Something:
def __init__(self):
print('init')
self.deco_function()
print('done')
if __name__ == '__main__':
a = Something()
代码运行完全正常,打印
init
do something
done
然而,VSCode在self.deco_function()
下加了红色下划线,pylint声明实例"Something"没有"deco_function"成员。
有没有办法阻止pylint标记它,或者让VSCode将deco_function识别为实例成员?
谢谢你的建议。
您必须使用PyLint插件来判断哪些类成员是运行时生成的
在PYTHONPATH
上的某个位置创建一个文件pylint_decorator.py
import astroid
from astroid import MANAGER
def register(linter):
# Needed for registering the plugin.
pass
def transform(cls):
if not cls.decorators: return
if any(map(lambda x: x.name == 'deco_function', cls.decorators.nodes)):
extension_module = astroid.parse("""
def deco_function(self):
pass
""")
for name, objs in extension_module.locals.items():
cls.locals[name] = objs
MANAGER.register_transform(astroid.ClassDef, transform)
然后使用以下设置配置VSC
"python.linting.pylintArgs": ["--load-plugins", "pylint_decorator"]
仅当使用@deco_function
语法时,此操作才有效。
如果调用decorator函数,PyLint将看不到decorator 的使用
# this use will not be catched by the plugin
class Something:
def __init__(self):
print('init')
self.deco_function()
print('done')
Something = deco_function(Something)