Class attributes are variables of a class that are shared between all of its instances. They differ from instance attributes in that instance attributes are owned by one specific instance of the class only, and are not shared between instances. This is highlighted in the illustration below:
Consider the following code snippet which highlights how different objects of a class share the same class attribute:
class classA(object):classAtr = "I am the same for all objects."def __init__(self, ins_var):self.instanceVar = ins_var# Make 3 objects and initialise them with different valuesobj1 = classA(5)obj2 = classA(10)obj3 = classA(15)print("I am obj1 and my attributes are: ")print("Class Attribute: ", obj1.classAtr)print("Instance Attribute:", obj1.instanceVar ,"\n")print("I am obj2 and my attributes are: ")print("Class Attribute: ", obj2.classAtr)print("Instance Attribute: ", obj2.instanceVar, "\n")print("I am obj3 and my attributes are: ")print("Class Attribute: ", obj3.classAtr)print("Instance Attribute: ", obj3.instanceVar, "\n")
Consider the following code snippet:
class classA(object):classAtr = "I am a class attribute."obj1 = classA()obj2 = classA()obj1.classAtr = "abc"print(obj1.classAtr)print(obj2.classAtr)
Assigning “abc” to obj1
's classAtr
did not change the value of the class attribute for obj2
. This is because class attributes must be changed using the class’s name, instead of the object’s name.
The following code snippet shows the correct way to change a class attribute:
class classA(object):classAtr = "I am a class attribute."obj1 = classA()obj2 = classA()classA.classAtr = "I changed the class attribute."print(obj1.classAtr)print(obj2.classAtr)
Free Resources