简体   繁体   中英

Why even when I don’t create a turtle object in python my code works

I am new to python and I am currently learning turtle module. And as long as I understand turtle is a module in which we have Turtle class, so doesn't this mean that first we need to create a Turtle object to use methods on this objects.

Like:

my=turtle.Turtle()

But when I just import turtle and write turtle.forward(50) this works but I didn't create any Turtle object, can someone please explain why this also works?

If you see the file turtle.py , If you don't create an object and call a function directly , it will create an object for you.

In the file turtle.py you can see in line 128 it defines a list _tg_turtle_functions of all the functions of a Turtle object.

In line 3856 you can see clearly that they eval an object and call the specific function you want.

As quarmarana wrote in the comments, this is simply a convenience for beginners. If you're curious about how this works you can actually see it in the code for the turtle module though it's a bit opaque as it's using some code generation hacks.

For most of the main methods on the Turtle class (eg Turtle.forward ) it generates a forward() function that's essentially just a wrapper for initializing a Turtle() and calling forward() on it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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