Dremendo Tag Line

Instance Variables in Python Programming

OOPs in Python

In this lesson, we will understand what is Instance Variable in Python Programming and how to create them along with some examples.

What are Instance Variables in Python?

We use Instance Variables to store values in an object. Each object has its own copy of instance variables that are not shared between other objects.

Instance variables are declared and initialized inside a unique method called Constructor. The first parameter of the constructor method is self which refers to the memory address of the instance (object) of the current class. Using self, we can access and modify the value of the instance variables of a class.

In python, the constructor is created with the __init__() method, which automatically gets executed when we create an object of a class.

video-poster

Example of creating Instance Variables using Constructor Method

class Record:

    # Creating instance variables using constructor method
    def __init__(self):
        self.name = ""
        self.age = 0

# Creating an object x of the class Record
x = Record()

In the above example, we have created two instance variables, name and age, and initialized their values as blank and 0, respectively. After that, we created an object x of the class Record.

We can also initialize the instance variables of a class at the time of creating an object by passing values to the parameterized constructor method. A parameterized constructor method takes more than one argument. See the example given below.

Example of creating and initializing Instance Variables using Parameterized Constructor Method

class Record:

    # Creating instance variables using parameterized constructor method
    def __init__(self, name, age):
        self.name = name
        self.age = age

# Creating an object x of the class Record
x = Record('Peter', 22)

In the above program, we are sending Peter and 22 as the values for the name and age variables of the parameterized constructor method. Then the values get initialized from name and age parameter variables to the class's name and age instance variables.

Note: It's not compulsory to have identical names for both parameter and instance variables, and we can use different names for parameter variables in parameterized constructors. See the example given below.

Parameterized Constructor Example 2

class Record:

    # Creating instance variables using parameterized constructor method
    def __init__(self, nm, ag):
        self.name = nm
        self.age = ag

# Creating an object x of the class Record
x = Record('Peter', 22)

Access and Modify Values of Instance Variables

We can access the value of an instance variable in two ways, first by using the object of the class followed by a dot (.) operator and then writing the name of the instance variable whose value we want to access, and second by using the getattr() function.

We can modify the value of an instance variable by using the object of the class followed by a dot (.) operator and then writing the name of the instance variable with an equal sign and then providing the new value to it or by using the setattr() function.

Syntax of getattr and setattr function

getattr(object_name, 'instance_variable_name')
setattr(object_name, 'instance_variable_name', value)

Note: The value should be enclosed within single or double quotes if the value is a string.

Access and Modify Instance Variables using dot operator

class Record:

    # Creating instance variables using parameterized constructor method
    def __init__(self, nm, ag):
        self.name = nm
        self.age = ag

# Creating an object x of the class Record
x = Record('Peter', 22)

# Values of instance variables before modification
print('Name: %s' %(x.name))
print('Age: %d' %(x.age))

# Modify the values of the instance variables
x.name = 'Thomas'
x.age = 25

# Values of instance variables after modification
print('Name: %s' %(x.name))
print('Age: %d' %(x.age))

Output

Name: Peter
Age: 22
Name: Thomas
Age: 25

Access and Modify Instance Variables using getattr and setattr functions

class Record:

    # Creating instance variables using parameterized constructor method
    def __init__(self, nm, ag):
        self.name = nm
        self.age = ag

# Creating an object x of the class Record
x = Record('Peter', 22)

# Values of instance variables before modification
print('Name:', getattr(x, 'name'))
print('Age:', getattr(x, 'age'))

# Modify the values of the instance variables
setattr(x, 'name', 'Thomas')
setattr(x, 'age', 25)

# Values of instance variables after modification
print('Name:', getattr(x, 'name'))
print('Age:', getattr(x, 'age'))

Output

Name: Peter
Age: 22
Name: Thomas
Age: 25

Get a list of all the Instance Variables of an Object

We can get a list of all the instance variables of an object in the form of a dictionary using the function __dict__.

Example

class Record:

    # Creating instance variables using parameterized constructor method
    def __init__(self, nm, ag):
        self.name = nm
        self.age = ag

# Creating an object x of the class Record
x = Record('Peter', 22)

# Display the list of all the instance variables of the object x
print(x.__dict__)

Output

{'name': 'Peter', 'age': 22}

Add New Instance Variable Dynamically to an Object

We can dynamically add a new instance variable to an object by writing the object name followed by a dot (.) operator and then writing the new name of the instance variable with an equal sign and then providing the new value. The newly added instance variable is only available in the object it has been added to. The newly added instance variable is not reflected in other objects of the same class.

Example

class Record:

    # Creating instance variables using parameterized constructor method
    def __init__(self, nm, ag):
        self.name = nm
        self.age = ag

# Creating two object x, y of the class Record
x = Record('Peter', 22)
y = Record('Thomas', 25)

# Add a new instance variable to object x
x.roll=1

# Display the list of all the instance variables of the object x
print(x.__dict__)

# Display the list of all the instance variables of the object y
print(y.__dict__)

Output

{'name': 'Peter', 'age': 22, 'roll': 1}
{'name': 'Thomas', 'age': 25}

Delete an Instance Variable Dynamically from an Object

We can dynamically delete an instance variable from an object using the del statement or delattr() function. The del statement or delattr() function will delete the instance variable only from the object it applied on and not from all the objects.

Syntax of delattr function

delattr(object_name, 'instance_variable_name')

Example

class Record:

    # Creating instance variables using parameterized constructor method
    def __init__(self, rn, nm, ag):
        self.rollno = rn
        self.name = nm
        self.age = ag

# Creating two object x, y of the class Record
x = Record(1,'Peter', 22)
y = Record(2,'Thomas', 25)

# Delete the instance variable rollno from object x
delattr(x,'rollno')

# Display the list of all the instance variables of the object x
print(x.__dict__)

# Display the list of all the instance variables of the object y
print(y.__dict__)

Output

{'name': 'Peter', 'age': 22}
{'rollno': 2, 'name': 'Thomas', 'age': 25}