python - PyCharm - from turtle import * -- 提供未使用的导入参考
问题描述
PyCharm 没有正确导入/解析。代码运行正常,但没有完成代码,并标记为错误(红色波浪线)。
演示这一点的代码如下:
from turtle import *
forward(40)
right(45)
forward(80)
import turtle
t = turtle.Turtle()
t.forward(40)
t.right(45)
t.forward(80)
还有一张在 PyCharm 中演示该问题的图片:
有没有人对如何解决这个问题有任何想法?无法使用非常烦人from X import Y
。
解决方案
根据经验,from X import *
无论 X 是什么包或它的文档说什么,都不要使用,它只会在以后导致错误。
为什么要避免“明星进口”
from turtle import *
def forward():
print('forward')
forward(45)
你认为会发生什么?
turtle.forward
被本地定义的forward
函数覆盖,我们会得到一个错误TypeError: forward() takes 0 positional arguments but 1 was given
为什么它在这种情况下有效
from turtle import *
forward(40)
要理解为什么即使 Pycharm 说forward
没有定义上述方法仍然有效,我们必须看看turtle
模块是如何实现的,然后了解 Python 导入是如何工作的,以及 Pycharm 如何检查使用名称的“定义”。
海龟.py
tg_classes = ['ScrolledCanvas', 'TurtleScreen', 'Screen',
'RawTurtle', 'Turtle', 'RawPen', 'Pen', 'Shape', 'Vec2D']
_tg_screen_functions = ['addshape', 'bgcolor', 'bgpic', 'bye',
'clearscreen', 'colormode', 'delay', 'exitonclick', 'getcanvas',
'getshapes', 'listen', 'mainloop', 'mode', 'numinput',
'onkey', 'onkeypress', 'onkeyrelease', 'onscreenclick', 'ontimer',
'register_shape', 'resetscreen', 'screensize', 'setup',
'setworldcoordinates', 'textinput', 'title', 'tracer', 'turtles', 'update',
'window_height', 'window_width']
_tg_turtle_functions = ['back', 'backward', 'begin_fill', 'begin_poly', 'bk',
'circle', 'clear', 'clearstamp', 'clearstamps', 'clone', 'color',
'degrees', 'distance', 'dot', 'down', 'end_fill', 'end_poly', 'fd',
'fillcolor', 'filling', 'forward', 'get_poly', 'getpen', 'getscreen', 'get_shapepoly',
'getturtle', 'goto', 'heading', 'hideturtle', 'home', 'ht', 'isdown',
'isvisible', 'left', 'lt', 'onclick', 'ondrag', 'onrelease', 'pd',
'pen', 'pencolor', 'pendown', 'pensize', 'penup', 'pos', 'position',
'pu', 'radians', 'right', 'reset', 'resizemode', 'rt',
'seth', 'setheading', 'setpos', 'setposition', 'settiltangle',
'setundobuffer', 'setx', 'sety', 'shape', 'shapesize', 'shapetransform', 'shearfactor', 'showturtle',
'speed', 'st', 'stamp', 'tilt', 'tiltangle', 'towards',
'turtlesize', 'undo', 'undobufferentries', 'up', 'width',
'write', 'xcor', 'ycor']
_tg_utilities = ['write_docstringdict', 'done']
__all__ = (_tg_classes + _tg_screen_functions + _tg_turtle_functions +
_tg_utilities + ['Terminator'])
...
如您所见,它只是准备了一些字符串列表(它们是函数/类/等的名称),然后将所有内容连接到一个列表并将所有内容分配给__all__
全局变量。
我不会详细介绍__all__
(因为关于该主题有几个关于 SO 的问答,例如Can有人在 Python 中解释 __all__ 吗?),但基本上它告诉解释器在做from X import *
.
当您执行from turtle import *
then usingforward
等right
时,它们可以使用,因为它们的名称在 inside __all__
,但 Pycharm 不知道它们会__all__
在运行时暴露。
推荐阅读
- php - Laravel:帖子类别未更新
- php - 调用 haveibeenpwned API 时出现 401 授权错误
- android - 如何从主要活动中适配器设置的接口获取值
- javascript - 在 jquery 中求和 Ajax 响应
- c - 初始化字符串并将其传递给函数
- asp.net-core - 如何读取 appsettings.json 方括号中的值
- android - 在android中生成具有16个字符初始化向量的32个字符的AES字符串
- angular - Angular 的 ag-Grid:支持的 Angular 版本
- sql - 如何在 SQL 中为单个标识符连接多个值?
- sql - INNER JOIN 中的表顺序