Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

python - Difference between turtle and Turtle?

How are turtle and Turtle different from each other in python version 2.7?

import turtle
star = turtle.Turtle()
for i in range(50):
    star.forward(50)
    star.right(144)
turtle.done()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The turtle module is unusual. To make it easier for beginning programmers, all methods of the Turtle class are also available as top level functions that operate on the default (unnamed) turtle instance. All methods of the Screen class are also available as top level functions that operate on the default (sole) screen instance. So both this:

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

and this:

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

are both valid implementations. Many turtle programs end up mixing the functional interface with the object interface. To avoid this, I strongly recommend the following import syntax:

from turtle import Turtle, Screen

This forces the object approach to using turtle, making the functional approach unavailable:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...