直接在 turtle 库上使用函数而不创建 class Turtle() 的对象

using function directly on turtle library without making object of class Turtle()

我正在使用 turtle 库并直接在其上应用函数。 但是我有点困惑,为什么即使我没有将它作为 class Turtle() 的对象,代码也能正常工作。 例如,turtle.color("red")turtle.forward(100) 在给定的代码

中工作正常
import turtle

screen = turtle.Screen()

turtle.color("red")

tim = turtle.Turtle()
tim.color("yellow")

turtle.forward(100)
tim.backward(150)
screen.exitonclick()

输出:

来自turtle documentation

The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways.

The object-oriented interface uses essentially two+two classes.

The procedural interface provides functions which are derived from the methods of the classes Screen and Turtle. They have the same names as the corresponding methods. A screen object is automatically created whenever a function derived from a Screen method is called. An (unnamed) turtle object is automatically created whenever any of the functions derived from a Turtle method is called.

To use multiple turtles on a screen one has to use the object-oriented interface.

假设我们有一个名为 bot.py 的模块。这是面向过程的脚本的示例:

name = None

def greet():
    print(f"Hello {name}!")

def chat():
    print(f"So {name}, how are you today?")

下面是一个面向对象的脚本示例:

class Bot:
    def __init__(self, name=None):
        self.name = name

    def greet(self):
        print(f"Hello {self.name}!")

    def chat(name):
        print(f"So {self.name}, how are you today?")

对于海龟模块,这两个选项都可用。