Difference between turtle and Turtle?

后端 未结 5 986
粉色の甜心
粉色の甜心 2021-01-22 20:16

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

import turtle
star = turtle.Turtle()
for i in ran         


        
相关标签:
5条回答
  • 2021-01-22 20:41

    The first turtle is called turtle and is referenced by it's name or it in a variable, the turtle.Turtle method creates a new turtle and (most of the time), you set it to a variable.

    0 讨论(0)
  • 2021-01-22 20:41

    Simply put, turtle is the package or library and Turtle() class constructor method used to instantiate the class.

    0 讨论(0)
  • 2021-01-22 20:50

    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
    
    0 讨论(0)
  • 2021-01-22 20:51

    turtle is the name of the package while Turtle is the name of the class.

    An alternate way of importing the module would be:

    import turtle.Turtle

    Also, are you sure the last line is turtle.done() and not star.done()?

    0 讨论(0)
  • 2021-01-22 21:00

    turtle is the module that you import while Turtle is that name of the class. Using from turtle import * removes the need for turtle.Turtle.

    0 讨论(0)
提交回复
热议问题