Class & Instance Attributes in Python

PythonServer Side ProgrammingProgramming

A class is a blueprint for the creation of different objects. When the objects get created to form the class, they no longer depend on the class attribute. Also, the class has no control over the attributes of the instances created.

In the below example we see the MainClass having a class attributes and the objects created from the main class having their own attribute values. Printing these values gives us clarity. In the end the class cannot access the values of the object attributes.

Example

class MainClass(object):  
   class_attr = 'Sun'
   def __init__(self, instance_attr):
      self.instance_attr = instance_attr
if __name__ == '__main__':
   obj1 = MainClass('Mon')
   obj2 = MainClass('Tue')
   # print the instance attributes
   print (obj1.instance_attr)
   print (obj2.instance_attr)
   #print the class attribute using Mainclass
   print(MainClass.class_attr)
   #print the classattribute using objects
   print (obj1.class_attr)
   print (obj2.class_attr)
   #printing instance attribute as a class property gives error
   #print (MainClass.instance_attr)

Output

Running the above code gives us the following result −

Mon
Tue
Sun
Sun
Sun
raja
Published on 17-Oct-2019 12:00:17
Advertisements