Andrew Walker Andrew Walker - 11 months ago 70
Python Question

Static class variables in Python

Is it possible to have static class variables or methods in python? What syntax is required to do this?


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

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

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:
    def f(arg1, arg2, ...): ...

@beidy recommends classmethods over staticmethod, as the method then receives the class type as the first argument, but I'm still a little fuzzy on the advantages of this approach over staticmethod. If you are too, then it probably doesn't matter.