繁体   English   中英

有没有办法缩短我的代码,这样我每次使用龟模块的功能时都不必写“乌龟”。

[英]Is there a way to shorten my code so that I don't have to write “turtle.” every time I use functions from the turtle module?

我试图在python中使用turtle绘制正方形,每次我想命令它做某事我必须写turtle

import turtle


turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.back(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.back(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.back(200)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.back(100)



turtle.exitonclick()

我希望每次编写我的代码而不必写turtle

您可以通过写入从turtle模块导入所有内容

from turtle import *  # this is a wildcard import

相反,你应该只是import turtle as t (或者你想要的任何其他东西),如下所示:

import turtle as t  # you can replace t with any valid variable name

因为通配符导入往往会产生函数定义冲突

相反,您只能从模块中导入所需的类(或方法)。 Turtle是必要的进口:

from turtle import Turtle

现在,我们必须实例化它:

t = Turtle()

现在我们可以使用它:

t.do_something()  # methods that act on the turtle, like forward and backward

但是,这不会导入Screen模块,因此除非您也导入Screen否则您将无法使用exitonclick()

from turtle import Turtle, Screen
s = Screen()
s.exitonclick()

正如@cdlane所指出的,循环可能实际上是减少你必须编写的代码量的最佳选择。 这段代码:

for _ in range(x):
    turtle.forward(100)
    turtle.right(90)

向前移动turtle然后向右移动x次。

您可以使用通配符导入:

from turtle import * 

但最好使用前缀导入来保持名称空间的清洁。 @ alec_a的回答

您是否知道有多少评论SO上写着“不要使用通配符导入”以回应人们from turtle import *做出的反应from turtle import *正如人们所建议的那样? 我会进一步争辩说,不要将import turtle as t暴露乌龟的功能接口。 乌龟模块是面向对象的 ,您只需要公开该接口。 如果你厌倦了打字这么多,请了解循环:

from turtle import Screen, Turtle

t = Turtle()

for _ in range(4):
    t.forward(100)
    t.right(90)

for _ in range(4):
    t.backward(100)
    t.left(90)

t.backward(100)

for _ in range(3):
    t.backward(100)
    t.left(90)

s = Screen()

s.exitonclick()

不可否认,对于简短的turtle和tkinter示例以及Zelle图形程序,我并不介意使用通配符导入。 但是没有那个fd()废话而不是forward() 庆祝成为一只乌龟,不要躲在你的壳里!

免责声明:这个答案适合像我这样的懒人:)

已经有很好的答案向您展示如何解决您的问题,并警告您有关通配符导入。

如果你只想玩龟模块你可以让你的生活变得轻松,也就是说,而不是写turtle.forward(90)最好只是forward(90)forward(90)但如果你只写f(90)就会非常容易

再一次,它会影响你的代码的可读性,但通常它应该得到一个试验

现在你的代码看起来像

编辑 :根据@chepner的建议修改一行中的导入为超级懒惰

from turtle import forward as f, back as b, right as r, left as l, exitonclick

# to draw one square
f(100)
r(90)
f(100)
r(90)
f(100)
r(90)
f(100)

exitonclick()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM