Search⌘ K
AI Features

Class Attributes and Instance Attributes

Understand the difference between class attributes and instance attributes in Python, how they are stored and accessed, and what issues arise when manipulating them. Learn to identify when an instance attribute is created versus referencing a class variable, helping you write cleaner and more predictable Python code.

We'll cover the following...

What could go wrong when using class variables like instance variables?

Python 3.5
class A:
x = 1
class B(A):
pass
class C(A):
pass
print(A.x, B.x, C.x)
B.x = 2
print(A.x, B.x, C.x)
A.x = 3
print(A.x, B.x, C.x) # C.x changed, but B.x didn't
a = A()
print(a.x, A.x)
a.x += 1
print(a.x, A.x)

Explanation

  • Class variables and variables in class instances are internally handled as dictionaries of a class object. If a variable name is not found in the dictionary of the current class, the parent classes are searched for it.
  • When we execute a.x += 1, which is equivalent to a.x = a.x + 1, an instance attribute is initialized. So, now the object a has an instance attribute named x, as well as a class attribute named x. The following snippet makes it clear:
Python 3.8
class A:
x = 3
a = A()
a.x += 1
print(a.x, a.__class__.x)