Skip to content

What is Class variable and Object variable in Python

Class variable and object variable in Python

In this tutorial we will learn about class variable and object variable in Python class . Before reading further we recommend to read about the below tutorial –

What is class variable and instance/object variable

A class variable is a variable that is defined within a class but outside of a class method. The class variable can be accessed by that class and all objects of that class. But if we want to change the value of a class variable, it can only be changed by class, It cannot be changed by any object. Class variables are also called class attribute and class property .

An instance/object variable is a variable that is defined within a class method or after an object creation outside the class. It can only be accessed and changed by the object. Object variables are also called object attribute and object property .

__dict__ attribute helps us to know what attributes are in an object or class.

If the class variable and the object variable have the same name, the object variable will overpower the class variable.

del keyword allows us to delete a class variable , object variable or an object.

Examples of Class variable and Object variable in Python

Example 1:

Defining a class
# creating a class named Myclass
class Myclass:
    # creating class variable
    total_student = 10

In the above code, first a class named Myclass has been created with a class variable named total_student.

Create two objects of the class
# creating two object of class Myclass
sourav = Myclass()
sudipta = Myclass()

Then two objects of Myclass class named sourav and sudipta have been created.

Create object variable in Python for both the objects
# creating object variable
# for sourav
sourav.roll_no = 8
sourav.age = 26

# for sudipta
sudipta.roll_no = 7
sudipta.age = 27

Then two instance variables roll_no and age have been created for each object. roll_no of sourav and sudipta is 8 and 7 . age of sourav and sudipta is 26 and 27

Access class variable in Python using class name and object name
# accessing class variable
# using classname
print(Myclass.total_student)

# using object name
print(sourav.total_student)
print(sudipta.total_student)
10
10
10

Then the class variable is accessed by the name of the class and the object , which has printed 10 in each case.

Try to change value of class variable in Python using object name
# Trying to change class variable
# using object name
sourav.total_student = 12
# If we can change class variable using
# object name then it will reflect for
# all the object and for the class
print(sourav.total_student)
print(sudipta.total_student)
print(Myclass.total_student)
12
10
10

Then an attempt have been made to change the class variable with the help of object name sourav with value 12. Then the class variable is accessed by the name of the class and the object. When the class variable is accessed by object_name sourav it prints 12 but when the class variable is accessed by object_name sudipta and class_name it prints 10 . So class variable cannot be changed by object name.

In fact, when sourav.total_student = 12 tried to change the class variable, instead of changing the class variable, an instance variable total_student of the sourav object was created and its value is 12. Now the sourav object has a class variable named total_student whose value is 10 and an instance variable whose value is 12. Since the instance variable overpowers the class variable, so when sourav.total_student was printed it printed 12.

Change value of class variable in Python using class name
# Trying to change class variable
# using class name
Myclass.total_student = 15
# If we can change class variable using
# class name then it will reflect for
# all the object and for the class
print(sourav.total_student)
print(sudipta.total_student)
print(Myclass.total_student)
12
15
15

Then the class variable has been changed to 15 with the help of class_name and then when the class variable has been printed with the help of class and object name it has printed 15 for everyone except sourav.

Print all the attributes that can be accessed using class name and object name
# check all variable of class and object
# using __dict__ attribute
print(Myclass.__dict__)
print(sourav.__dict__)
print(sudipta.__dict__)
{'__module__': '__main__', 'total_student': 15, '__dict__': <attribute '__dict__' of 'Myclass' objects>, '__weakref__': <attribute '__weakref__' of 'Myclass' objects>, '__doc__': None}
{'roll_no': 8, 'age': 26, 'total_student': 12}
{'roll_no': 7, 'age': 27}

We can also check with the help of __dict__ attribute that sourav object has an instance variable called total_student in addition to roll_no and age whose value is 12.

Change the value of object variable in Python
# changing object variable of sourav
# before changing
print(sourav.roll_no)
# changing
sourav.roll_no = 4
# after changing
print(sourav.roll_no)
8
4

Then instance variable roll_no of the sourav object was accessed which printed 8, then changed and then accessed again which printed the changed value 4.

Delete an object variable in Python
# deleting object variable total_student
# of sourav object
del sourav.total_student
print(sourav.__dict__)
{'roll_no': 4, 'age': 26}

Then object variable total_student of the sourav object has been deleted and with the help of __dict__ attribute we can see that the object variable total_student has been deleted.

Delete a class variable in Python
# deleting class variable total_student
del Myclass.total_student
print(Myclass.__dict__)
{'__module__': '__main__', '__dict__': <attribute '__dict__' of 'Myclass' objects>, '__weakref__': <attribute '__weakref__' of 'Myclass' objects>, '__doc__': None}

Similarly, the class variable total_student has been deleted and checked with the __dict__ attribute.

Delete an object in Python
# deleting sourav object
del sourav
print(sourav)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
C:\Users\RAJKUM~1\AppData\Local\Temp/ipykernel_11340/2226975288.py in <module>
1 #deleting sourav object
2 del sourav
----> 3 print(sourav)

NameError: name 'sourav' is not defined

Finally the sourav object has been deleted, so when trying to print the sourav it raised NameError.

In addition to these general rules, there are some functions with which we can access, modify, delete various object variables. These are provided by a list –

  • getattr(object _name , variable_name) = With this function we get the value of the given variable of the given object, if the given variable does not exist then it will raise error.
  • hasattr(object _name , variable_name) = This function allows us to find out whether the given variable is in the given object or not . If the given variable is in the given object then it will return True else False .
  • setattr(object _name , variable_name , value) = With this function we can change the value of the given variable of the given object if the variable exists, if not then a variable of the given name will be created with that value.
  • delattr(object _name , variable_name) = With this function we can delete the given variable of the given object if the variable exists, otherwise it will raise error.

Example 2:

# creating a class named Myclass
class Myclass:
    # creating class variable
    total_student = 10
# creating a object of class Myclass
sourav = Myclass()
# creating object variable
# for sourav object
sourav.roll_no = 8
sourav.age = 26
Access an object variable in Python using getattr() function
# to get value of object variable
print(getattr(sourav, "age"))
print(getattr(sourav, "height")) # error
26

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
C:\Users\RAJKUM~1\AppData\Local\Temp/ipykernel_12788/3145639801.py in <module>
1 #to get value of object variable
2 print(getattr(sourav, "age"))
----> 3 print(getattr(sourav, "height")) # error

AttributeError: 'Myclass' object has no attribute 'height'
Check if an object variable in Python is present or not using hasattr() function
# to check if object variable present or not
print(hasattr(sourav, "age"))
print(hasattr(sourav, "height")) 
True
False
Create object variable in Python using setattr() function
# to set object variable's value if present
# else create with that value
print(sourav.__dict__)
setattr(sourav, "age", 28)
setattr(sourav, "height", 170)
print(sourav.__dict__)
{'roll_no': 8, 'age': 26}
{'roll_no': 8, 'age': 28, 'height': 170}
Delete an object variable in Python using delattr() function
# to delete object variable 
delattr(sourav, "age")
print(sourav.__dict__)
delattr(sourav, "age")
{'roll_no': 8, 'height': 170}

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
C:\Users\RAJKUM~1\AppData\Local\Temp/ipykernel_12788/3766175734.py in <module>
2 delattr(sourav, "age")
3 print(sourav.__dict__)
----> 4 delattr(sourav, "age")

AttributeError: age

Thank you for reading this Article . If You enjoy it Please Share the article . If you want to say something Please Comment .

Leave a Reply