HOWTO · Python

How to Define a Class Global Variable in Python

Learn to define a Python class attribute in the class body, access it with ClassName.attribute, and distinguish it from a module-level name declared with global.

On this page

A Python class variable is an attribute assigned in the class body. Define it once on the class, then read it with ClassName.attribute, such as Tesla.speed. A global name is separate: it belongs to the module namespace and does not become a class attribute.

Define a Class Variable in Python

Assign the value in the class body, then read it with the class name. The example also shows a method and a second class reading the same attribute.

class Tesla:
    speed = 60

    def show_speed(self):
        return Tesla.speed


class Dashboard:
    def show_tesla_speed(self):
        return Tesla.speed


print(Tesla.speed)
print(Tesla().show_speed())
print(Dashboard().show_tesla_speed())
60
60
60

Here, speed is stored on Tesla, so Tesla.speed reads the shared class attribute. The method in Tesla and the method in Dashboard both use the same class-qualified lookup.

Access a Class Variable Outside Its Class

Use ClassName.attribute wherever the class is available. For example, Tesla.speed works in module-level code and in another class method. Creating an instance is not required to read a class attribute. A bare name such as speed outside the class does not refer to Tesla.speed; it is looked up in the current scope and may be undefined.

An instance can also define an attribute with the same name. For example, car.speed = 80 sets an attribute on that particular car, while Tesla.speed still refers to the class attribute. Use the class-qualified form when you specifically need the shared value.

Why global Does Not Define a Class Variable

The global statement tells Python that an assignment to a bare name in a code block should bind that name in the module namespace. In a class body, global speed followed by speed = 60 creates or updates the module-level name speed; it does not assign Tesla.speed. To define a class variable, write an assignment such as speed = 60 in the class body without global, and access it as Tesla.speed outside the class.

A method that needs the class attribute can also use Tesla.speed. If the method should work with subclasses, use type(self).speed or self.speed according to the intended lookup behavior; self.speed can resolve an instance attribute that shadows the class attribute.