NEXT TUTORIAL >> Class Variables and Class methods
Instance variables are the variables whose value is assigned inside a constructor (__init__) or a method with self.
In Instance variables, a separate copy of variable is maintained for every instance or object.
To understand this, consider ‘n’ is an instance variable and if we create 2 two instances, then, there will be two copies for same variable ‘n’.
If we modify one copy of ‘n’ in any of two instance, then, it will not modify other one.
Let’s see one example,
class Test:
# constructor
def __init__(self):
# instance variable
self.count = 1
def modify(self):
self.count += 1
# creating 2 instances of our class Test
i1 = Test()
i2 = Test()
print('count for i1 : ', i1.count)
print('count for i2 : ', i2.count)
print('modifying count for i2')
i2.modify()
print('count for i1 now: ', i1.count)
print('count for i2 now: ', i2.count)
O/P
count for i1 : 1
count for i2 : 1
modifying count for i2
count for i1 now: 1
count for i2 now: 2
In the above code, we created two copies for variable count, and upon modifying one copy, other one was not modified.
Instance methods
Instance methods are the methods that work with instance variables in a class. Hence, instance methods performs a set of actions on the value provided by the instance variables.
An Instance method is bound to the object of the class. It can access or even modify the object state by changing the value of a instance variables.
Any method in a class, until not specified, is treated as an Instance method.
In an Instance method, self is the first parameter that is passed by default.
Instance method defined inside a class can be accessed using ‘.‘ (dot) operator.
instancename.method()
Let’s try to create a Student database using Instance methods and variables,
class Student:
def __init__(self, name, rollno, marks):
self.name = name #instance variable
self.rollno = rollno #instance variable
self.marks = marks #instance variable
# instance method
def getStudent(self):
print('\nDetails provided')
print('Name : ', self.name)
print('Roll Number : ', self.rollno)
print('Marks : ', self.marks)
s1 = Student('Arjun', '121', '98%')
s2 = Student('Karna', '122', '95%')
# calling instance method
s1.getStudent()
s2.getStudent()
O/P
Details provided
Name : Arjun
Roll Number : 121
Marks : 98%
Details provided
Name : Karna
Roll Number : 122
Marks : 95%
That’s all here.
NEXT TUTORIAL >> Class Variables and Class methods
