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

Viewed 43

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?

2 Answers

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 (e.g. Turtle.forward) it generates a forward() function that's essentially just a wrapper for initializing a Turtle() and calling forward() on it.

Related