Search code examples
pythonclassstaticclass-variables

Class (static) variables and methods


How do I create class (i.e. static) variables or methods in Python?


Solution

  • Variables declared inside the class definition, but not inside a method are class or static variables:

    >>> class MyClass:
    ...     i = 3
    ...
    >>> MyClass.i
    3 
    

    As @millerdev points out, this creates a class-level i variable, but this is distinct from any instance-level i variable, so you could have

    >>> m = MyClass()
    >>> m.i = 4
    >>> MyClass.i, m.i
    >>> (3, 4)
    

    This is different from C++ and Java, but not so different from C#, where a static member can't be accessed using a reference to an instance.

    See what the Python tutorial has to say on the subject of classes and class objects.

    @Steve Johnson has already answered regarding static methods, also documented under "Built-in Functions" in the Python Library Reference.

    class C:
        @staticmethod
        def f(arg1, arg2, ...): ...
    

    @beidy recommends classmethods over staticmethod, as the method then receives the class type as the first argument.