【问题标题】:E1101:Module 'turtle' has no 'forward' memberE1101: 模块 'turtle' 没有 'forward' 成员
【发布时间】:2019-03-24 22:50:06
【问题描述】:

我是编程新手,我下载了 Python 并让它在 Visual Studio Code 中运行。我在搞乱海龟模块及其功能。

函数本身可以工作,但pylint 将其标记为错误并说没有像我编码的那样的“成员”。

我将如何解决这个错误? (我不想将其设置为“忽略”问题,而是要认识到我输入的代码是有效的并且来自 turtle 模块)

【问题讨论】:

标签: python visual-studio-code turtle-graphics pylint


【解决方案1】:

turtle 模块公开了两个接口,一个功能接口和一个面向对象接口。功能接口是在加载时从面向对象接口以编程方式派生的,因此静态分析工具看不到它,因此您的pylint 错误。而不是功能接口:

import turtle

turtle.forward(100)

turtle.mainloop()

对于pylint生成no-member,尝试使用面向对象的接口:

from turtle import Screen, Turtle

screen = Screen()

turtle = Turtle()

turtle.forward(100)

screen.mainloop()

这个针对龟的特殊import 屏蔽了功能接口,我推荐它,因为人们经常通过混合 OOP 和功能接口遇到错误。

【讨论】:

  • 这非常有帮助。谢谢! ?
【解决方案2】:

上面提到的函数是由代码生成的。 PyLint 只做静态分析。

我写了一个 astroid brain(插件)来帮助 PyLint 使用的 Python 解析器添加这些功能。

找到您安装 PyLint 的位置(目录以 Lib\site-packages\pylintLib/site-packages/pylint 结尾。

pylint 旁边是一个目录astroid

在目录Lib\site-packages\astroid\brainLib/site-packages/astroid/brain创建一个文件brain_turtle.py,内容如下:

import astroid

def register(linter):
  pass

def transform():
  import turtle
  def _make_global_funcs(functions, cls):
    funcs = []
    for methodname in functions:
      method = getattr(cls, methodname)
      paramslist, argslist = turtle.getmethparlist(method)
      if paramslist == "": continue
      funcs.append(f"def {methodname}{paramslist}: return")
    return funcs
  funcs = []
  funcs.extend(_make_global_funcs(turtle._tg_screen_functions, turtle._Screen))
  funcs.extend(_make_global_funcs(turtle._tg_turtle_functions, turtle.Turtle))
  return astroid.parse('\n'.join(funcs))

astroid.register_module_extender(astroid.MANAGER, "turtle", transform)

根据 PyLint 的 IDE 集成,您可能需要重新启动 IDE。

我还创建了一个astroid issue 来将此大脑添加到 PyLint (Astroid) 的下一次更新中

您也可以将此文件与pylint--load-plugins 命令行选项一起使用。请参阅PyLint documentation for IDE integration。使用的文件需要在你的PYTHONPATH

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多