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:

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

Watch a course Python - The Practical Guide

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

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:

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:

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:

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:

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

instance = MyClass()
instance.static_method()