turtle 模块异常。为了使初学者更容易,Turtle 类的所有方法也可用作对默认(未命名)turtle 实例进行操作的顶级函数。 Screen 类的所有方法也可用作在默认(唯一)屏幕实例上操作的顶级函数。所以这两个:
import turtle
star = turtle.Turtle() # turtle instance creation
for i in range(5):
star.forward(50) # turtle instance method
star.right(144) # turtle instance method
screen = turtle.Screen() # access sole screen instance
screen.mainloop() # screen instance method
还有这个:
import turtle
for i in range(5):
turtle.forward(50) # function, default turtle
turtle.right(144)
turtle.done() # function, mainloop() synonym, acts on singular screen instance
都是有效的实现。许多海龟程序最终将功能接口与对象接口混合在一起。为避免这种情况,我强烈推荐以下导入语法:
from turtle import Turtle, Screen
这会强制对象方法使用turtle,使函数方法不可用:
from turtle import Turtle, Screen
star = Turtle() # turtle instance creation
for i in range(5):
star.forward(50) # turtle instance method
star.right(144) # turtle instance method
screen = Screen() # access sole screen instance
screen.mainloop() # screen instance method