首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >VSCode,Python3.7:自定义修饰类的pylint无成员错误

VSCode,Python3.7:自定义修饰类的pylint无成员错误
EN

Stack Overflow用户
提问于 2020-11-11 22:12:17
回答 1查看 181关注 0票数 0

我最近将一个实例方法移出了它的类定义,并将其作为全局函数(例如: deco_function),以便能够在不同的类中再次使用它。详细解释和bug重现请参见以下代码:

代码语言:javascript
复制
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()

代码运行完全正常,正在打印

代码语言:javascript
复制
init
do something
done

但是,VSCode在self.deco_function()红色下划线,并使用pylint声明,实例'Something‘没有'deco_function’成员。

有没有办法防止pylint标记这一点,或者让VSCode将deco_function识别为实例成员?

谢谢你的建议。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-11 22:52:51

您必须使用PyLint插件来确定哪些类成员是在运行时生成的

PYTHONPATH上的某个位置创建文件pylint_decorator.py

代码语言:javascript
复制
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

代码语言:javascript
复制
"python.linting.pylintArgs": ["--load-plugins", "pylint_decorator"]

只有在使用@deco_function语法的情况下,这才有效。

如果调用装饰器函数,PyLint将看不到装饰器的用法

代码语言:javascript
复制
# 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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64788077

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档