Python Class Variables

A Class variable in Python is a variable that is accessible via the class rather than via an individual instance of the class. It's a variable shared among the class as a whole. Other languages sometimes refer to these as static variables or static fields.

Example

Python
class AttributeClass():
     x = 5

print(AttributeClass.x)

Output

5

Notes

Class attributes are sort of equivalent to what are called "static fields" in other programming languages. Consider this code:

Python
class MyClass():
    classVariable = 7

print(MyClass.classVariable)  # output is: 7

Notice we're not creating an object of type MyClass. Instead, we're referring to MyClasss directly.

We can refer to class variables via class instances:

Python
object = MyClass()
print(object.classVariable)   # output is again 7

We can change the class variable and it will be reflected in all instances

Python
object = MyClass()

MyClass.classVariable = 10    # change the value for the whole class

print(object.classVariable)   # output is now 10

What if we change the class variable by referring to an instance of the class instead of the class itself? In this case the class variable changes to start acting like an instance variable

Python
object = MyClass()           # Remember that classVariable is initially 7

object.classVariable = 5     # Let's change classVariable for an individual instance
print(object.classVariable)  # Output is 5. We're referring to the instance now

print(MyClass.classVariable) # output is 7. We're referring to the shared class value

Class variable are very useful for handling values that should be shared by all instances of a class. Use with caution, though, because it can be very confusing when the class variable is used like an instance variable.