Class Attributes

Variables that the class itself defines can be accessed simply by using the class name.

Example

Python
class AttributeClass():
     x = 5

print(AttributeClass.x)

Output

5

Notes

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

Python
class MyClass():
    x = 7

print(MyClass.x)

class1 = MyClass()
class1.x = 10
print(MyClass.x)

class2 = MyClass()
print(class2.x)

Output

7
7
7

Notice that changing x in the instance class1 doesn't change x for anyone.  However, look at this code:

Python
class MyClass():
    x = 7

MyClass.x = 12
print(MyClass.x)

class1 = MyClass()
class1.x = 10
print(MyClass.x)

class2 = MyClass()
print(class2.x)

Output

12
12
12

When we change the value of the class attribute, now instance gets that new value, but notice that class2 sees the "global" class attribute value of 12 rather than the 10.

Class attributes are very useful for global things about a class but should be used with caution because it can be very confusing when the class attribute is used like an instance attribute.