HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCritical

Class (static) variables and methods

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
methodsstaticandclassvariables

Problem

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.

Code Snippets

>>> class MyClass:
...     i = 3
...
>>> MyClass.i
3
>>> m = MyClass()
>>> m.i = 4
>>> MyClass.i, m.i
>>> (3, 4)
class C:
    @staticmethod
    def f(arg1, arg2, ...): ...

Context

Stack Overflow Q#68645, score: 2401

Revisions (0)

No revisions yet.