Python Instance Variables with Examples

Posted in

Python Instance Variables with Examples
vinaykhatri

Vinay Khatri
Last updated on October 31, 2024

    When we deal with Python classes and objects, there we have different types of variables.

    1. Instance Variables

    These variables are also known as attributes and fields of an object. The instance variables are associated with the object of the class. The variables that we create using __init__() method is generally known as instance variables.

    class Variables:
        def __init__(self, a, b):
            self.a = a     #self.a is an instance variable
            self.b = b     # self.b is an instance variable

    2. Local Variables

    The variables that are limited for a class method are known as local variables. The scope of the local variables is limited to the method definition.

    class Variables:
    
        def new_variables(self):
            a = 20    #a is a local variable
            b = 30    #b is also a local variable

    3. Parameters Variables

    Parameters are the variables that are passed in the method. The parameters variables are similar to the local variable, and their scope is also limited to that particular method.

    class Variables:
        def new_variables(self,c,d):
            a = c    #c is a parameter variable
            b = d    #d is also a parameter variable

    4. Class Variables

    Class Variables are shared among all the objects of the class. A class variable can also be considered as a global variable for all the class methods.

    class Variables:
        a = 20     #a is a class variable
        b = 30     #b is a also a class variable

    In this Python tutorial, we will see what is an Instance Variable in Python and how to initialize & use it. By the end of this tutorial, you will be able to understand the following topics.

    • What is an instance variable in Python?
    • How to initialize/create and access an instance variable in Python.
    • How to modify the value of an instance variable.
    • How to add and delete an instance variable dynamically.
    • What is the scope of an instance variable?

    What is an instance variable in Python?

    As the name suggests an instance variable is a variable that is associated with a particular instance or object(we can use the term instance and class object interchangeably, they both mean the same. A Class can have multiple instances or objects, and the value of instance variables may vary from one object to another.

    How to create an instance variable?

    To initialize or declare an instance variable we use the self keyword followed by the . operator and the variable name, such as self.name and self.data here self is the first argument value to the method that represents the instance of the object that is calling that method. We generally use the Python constructor or __init__(self) method to initialize the value of the instance variable for an instance.

    Example

    class Employee:
        def __init__(self, name, salary):
            self.name = name
            self.salary = salary
    
        def show_detail(self):
            print("Name:" ,self.name)   #access instance variable inside the class
            print("Salary", self.salary)
    
    #e1 is the instance/object of class Employee
    e1 = Employee("Rahul", 20000)
    e1.show_detail()
    
    print()
    
    #e2 is another instance of class Employee
    e2 = Employee("Kiran", 37984)
    e2.show_detail()

    Output

    Name: Rahul
    Salary 20000
    
    Name: Kiran
    Salary 37984

    In the above example the variables self.name and self.salary are the instance variables. And the value of both the variables is dynamic, depending upon the instance.

    Take Away Points

    1. We can create instance variables with the help of the Python class __init__() method.
    2. When we create a new object of the class the values passed to the class name parameter goes to the __init__() method.
    3. Only those variables that are defined or declared inside the __init__() method using the self keyword are will be treated as instance variables because only those variables depend upon the instance or object of the class.

    Ways to access the Instance Variables

    There are two ways to access an instance variable

    • Using the self (inside the class methods)
    • Using the object name (outside the class)

    Access the Instance variable within the class Instance Methods

    To access the instance variable within the class we can use the self name followed by the dot operator and the variable name.

    Example

    class Employee:
    
        def __init__(self, name, salary):
            self.name = name
            self.salary = salary
    
        def show_detail(self):
            print("Name:" ,self.name)   #access instance variable inside the method
            print("Salary", self.salary)
    
    #e1 is the instance/object of class Employee
    e1 = Employee("Rahul", 20000)
    e1.show_detail()

    Output

    Name: Rahul
    Salary 20000

    In every class’s instance method, self is the first parameter value, that represents the object that is calling that method.

    Access the Instance variable outside the class Instance Methods

    We can also access the instance variables outside the class using the object name. To access the instance variables outside the class we use the object name followed by dot operator then the variable name.

    Example

    class Employee:
        def __init__(self, name, salary):
            self.name = name
            self.salary = salary
    
    #e1 and e2 are the instances/objects of class Employee
    e1 = Employee("Rahul", 20000)
    e2 = Employee("Kiran", 66000)
    
    #access the instance variables outside the class
    print("Employee 1:", e1.name)
    print("Employee 2:", e2.name)

    Note : While accessing the instance variable outside the class we do not need to specify the self , because self and the instance name are the same things.

    How to modify the value of an instance variable

    To modify the value of an instance variable we first need to access it using the instance (self, or instance name), then assign a new value to it.

    Note: When we modify the value of an instance it will only affect the variable for that particular instance and have no effect on other instances.

    Example

    class Employee:
        def __init__(self, name, salary):
            self.name = name
            self.salary = salary
    
    #e1 is the instance/object of class Employee
    e1 = Employee("Rahul", 20000)
    
    print("Employee 1 name before modification:", e1.name)
    
    #modify the e1 object name instance variable
    e1.name = "rahul sharma"
    
    print("Employee 1 name after modification:", e1.name)

    Output

    Employee 1 name before modification: Rahul
    Employee 1 name after modification: rahul sharma

    In this example, we modified the instance variables using outside the class using the instance name. We can also modify the variables inside the class using the self.

    Example

    class Employee:
        def __init__(self, name, salary):
            self.name = name
            self.salary = salary
    
        def edit_name(self,new_name):
            self.name = new_name   #modify instance variable
    
    #e1 is the instance/object of class Employee
    e1 = Employee("Rahul", 20000)
    
    print("Employee 1 name before modification:", e1.name)
    
    #modify the e1 object name instance variable
    e1.edit_name("rahul sharma")
    
    print("Employee 1 name after modification:", e1.name)

    Output

    Employee 1 name before modification: Rahul
    Employee 1 name after modification: rahul sharma

    Naming conventions for the Instance variables

    The naming convention for instance variables is similar to the Python identifier or normal variables.

    1. The name should be all lower case. For example age = 34
    2. To separate the variable name should use the underscore character. For example user_salary= 343544
    3. The private variable should start with a single underscore. For example _key = 3432
    4. Use the double __ before the variable name for name mangaling(Python interpreter rewrites the name in such a way that it avoid conflict in the subclass). For Example __value = "some data"

    How to add and delete an instance variable dynamically

    By far we have been using the __init__() method to initialize instance variables. Now let’s discuss a new syntax to add a new instance variable dynamically outside the function.

    Syntax

    instanceName.new_instance_variable_name = value

    Example

    class Employee:
        def __init__(self, name, salary):
            self.name = name
            self.salary = salary
    
    #the instance/object of class Employee
    e1 = Employee("Rahul", 20000)
    e2 = Employee("Jay", 34324)
    
    #add a new instance variable for e1
    e1.status = "Manager"
    
    print("Employee 1 Status", e1.status)
    
    #error
    print("Employee 2 Status", e2.status)

    Output

    Employee 1 Status Manager
    
    Traceback (most recent call last):
      File "C:\Users\admin\AppData\Local\Programs\Python\Python310\main.py", line 18, in <module>
        print("Employee 2 Status", e2.status)
    AttributeError: 'Employee' object has no attribute 'status'

    In this example, we are receiving the error for e2.status because there is no status attribute for the e 2 object. We have only defined the status instance dynamically for the e1 object. As status is a dynamic instance object it can only be accessed through the e1 object.

    Note:

    • The dynamically added instance variable outside the class does not add the instance variable to the class but to the object only.
    • After adding an instance variable to a specific instance its changes do not reflect on the other objects.

    Dynamically delete the instance variable

    To delete an instance for a specific instance or object we can either use the del keyword or the delattr() function del keyword can delete any Python object, and we can use it to delete the instance variable

    Example

    class Employee:
        def __init__(self, name, salary):
            self.name = name
            self.salary = salary
    
    #the instance/object of class Employee
    e1 = Employee("Rahul", 20000)
    
    print("Before deleting the e1 salary variable", e1.salary)
    
    #delete the e1.salary
    del e1.salary
    
    #error
    print("after deleting the e1 salary variable", e1.salary)

    Output

    Before deleting the e1 salary variable 20000
    
    Traceback (most recent call last):
      File "C:\Users\admin\AppData\Local\Programs\Python\Python310\main.py", line 16, in <module>
        print("after deleting the e1 salary variable", e1.salary)
    AttributeError: 'Employee' object has no attribute 'salary'

    delattr() function stands for delete attribute and using this inbuilt Python function we can delete the object instance variable.

    Syntax

    delattr(object_name, variable_name)

    object_name is the name of instance which attribute which we want to delete varible_name is the name of the instance variable that we want to delete

    Example

    class Employee:
        def __init__(self, name, salary):
            self.name = name
            self.salary = salary
    
    #the instance/object of class Employee
    e1 = Employee("Rahul", 20000)
    
    print("Before deleting the e1 salary variable", e1.salary)
    
    #delete the e1.salary
    delattr(e1, salary)
    
    #error
    print("after deleting the e1 salary variable", e1.salary)

    Output

    Before deleting the e1 salary variable 20000
    
    Traceback (most recent call last):
      File "C:\Users\admin\AppData\Local\Programs\Python\Python310\main.py", line 13, in <module>
        delattr(e1, salary)
    NameError: name 'salary' is not defined

    Scope of an Instance variable

    The scope of an instance variable is limited to the class where it is defined. But in inheritance, the scope of the instance variable extends from one class to more. With the help of Python inheritance , we can access the instance variable of one class from another.

    Example

    class Car:
        def __init__(self):
            #instance variable of car class
            self.wheels = 4
    
    class BMW(Car):
        def __init__(self, model):
            #call the parent class
            super().__init__()
    
            self.model= model
    
        def detail(self):
            print("Car Model:", self.model)
            print("Car wheels:", self.wheels) #access the Car wheel from BMW 
    
    bmw = BMW("BMW X3")
    
    bmw.detail()

    Output

    Car Model: BMW X3
    Car wheels: 4

    How to list all the Instance variables of an Object?

    Every class object comes with an inbuilt __dict__ property which returns a dictionary of all the instance variables available for an object.

    Syntax

    obj.__dict__

    Example

    class Car:
        def __init__(self):
            #instance variable of car class
            self.wheels = 4
    
    class BMW(Car):
        def __init__(self, model):
            #call the parent class
            super().__init__()
            self.model= model
    
        def detail(self):
            print("Car Model:", self.model)
            print("Car wheels:", self.wheels) #access the Car wheel from BMW 
    
    bmw = BMW("BMW X3")
    
    print("All instance variables of bmw", bmw.__dict__)

    Output

    All instance variables of bmw {'wheels': 4, 'model': 'BMW X3'}

    Conclusion

    In this Python tutorial, we discussed what is an instance variable in Python and how to initialize or create it. The instance variables defined in the class are controlled by the objects of the class. Every object of the class has a copy of its own instance variables. We can add, modify, delete and list all the instances variable of an object. To add a new instance variable we can use the object name with dot operator new instance variable name and assign a value to it. Similarly, we can access an instance variable using the object name. To delete the instance variable for a particular instance we can use del keyword or delattr() function. And finally, to list all the available instance variables for an object we can take the help of object __dict__ property.

    People are also reading:

    Leave a Comment on this Post

    0 Comments