Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are static class variables possible in Python?

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

like image 643
Andrew Walker Avatar asked Sep 16 '08 01:09

Andrew Walker


People also ask

Does Python have static class variables?

When we declare a variable inside a class but outside any method, it is called as class or static variable in python. Class or static variable can be referred through a class but not directly through an instance.

Can a static class have variables?

Class variables are also known as static variables, and they are declared outside a method, with the help of the keyword 'static'. Static variable is the one that is common to all the instances of the class. A single copy of the variable is shared among all objects.

How do static variables work in Python?

A static variable in Python is a variable that is declared inside a defined class but not in a method. This variable can be called through the class inside which it is defined but not directly. A Static variable is also called a class variable.


1 Answers

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.

like image 61
Blair Conrad Avatar answered Oct 05 '22 12:10

Blair Conrad