乌龟和乌龟的区别?

Jdp*_*hit 3 python turtle-graphics python-2.7 python-turtle

python 2.7版中的turtleTurtle有什么不同?

import turtle
star = turtle.Turtle()
for i in range(50):
    star.forward(50)
    star.right(144)
turtle.done()
Run Code Online (Sandbox Code Playgroud)

cdl*_*ane 5

海龟模块不寻常。为了让初学者更容易,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
Run Code Online (Sandbox Code Playgroud)

和这个:

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
Run Code Online (Sandbox Code Playgroud)

都是有效的实现。许多海龟程序最终将功能接口与对象接口混合在一起。为了避免这种情况,我强烈推荐以下导入语法:

from turtle import Turtle, Screen
Run Code Online (Sandbox Code Playgroud)

这迫使对象方法使用乌龟,使函数方法不可用:

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
Run Code Online (Sandbox Code Playgroud)