Skip to content

Class (static) variables and methods

In Python, class variables are variables that are shared by all instances of a class. They are defined within the class definition, but outside of any of the class's methods. Class variables are owned by the class itself, and not by any instance of the class.

Here is an example of how you might define a class with a class variable in Python:

Define a class with a class variable in Python

python
class MyClass:
    # This is a class variable
    class_variable = "This is a class variable"

    def __init__(self, value):
        # This is an instance variable
        self.instance_variable = value

<div class="alert alert-info flex not-prose"> Watch a course Python - The Practical Guide</div>

You can access the value of a class variable by using the name of the class, followed by the variable name, like this:

Define a class with a class variable in Python and access the variable

python
class MyClass:
    # This is a class variable
    class_variable = "This is a class variable"

    def __init__(self, value):
        # This is an instance variable
        self.instance_variable = value

print(MyClass.class_variable)

You can also access the value of a class variable through an instance of the class, like this:

Access the value of a class variable through an instance of the class in Python

python
class MyClass:
    # This is a class variable
    class_variable = "This is a class variable"

    def __init__(self, value):
        # This is an instance variable
        self.instance_variable = value

instance = MyClass("this is an instance variable")
print(instance.class_variable)

Static methods are methods that belong to a class rather than an instance of the class. They are defined using the @staticmethod decorator.

Here is an example of how you might define a static method in Python:

Define a static method for a class in Python

python
class MyClass:
    @staticmethod
    def static_method():
        # This is a static method
        print("This is a static method")

You can call a static method by using the name of the class, followed by the method name, like this:

Access a static method of a class in Python

python
class MyClass:
    @staticmethod
    def static_method():
        # This is a static method
        print("This is a static method")

MyClass.static_method()

You can also call a static method through an instance of the class, like this:

Access a static method of a class through an instance of the class in Python

python
class MyClass:
    @staticmethod
    def static_method():
        # This is a static method
        print("This is a static method")

instance = MyClass()
instance.static_method()

Dual-run preview — compare with live Symfony routes.