Published Aug. 3, 2023, 1:43 p.m.
If the value of a variable varies from object to object, then such type of variables are called instance variables.
For every object, a separate copy of instance variables will be created.
We can declare instance variables inside a constructor by using the self
keyword. Once we create an object, these variables will be automatically added to the object.
Example:
class Person:
def __init__(self):
self.name = 'John' # Instance variable 'name' with value 'John'
self.age = 30 # Instance variable 'age' with value 30
self.is_student = True # Instance variable 'is_student' with value True
person1 = Person() # Creating an object 'person1' of the Person class
print(person1.__dict__) # Output: {'name': 'John', 'age': 30, 'is_student': True}
Explanation:
Person
with an __init__
method, which serves as the constructor for the class.name
, age
, and is_student
, each initialized with specific values ('John', 30, and True).person1
of the Person
class by calling the constructor Person()
.person1.__dict__
.person1
. In this case, name
is 'John', age
is 30, and is_student
is True.Note: When we create multiple objects of the Person
class, each object will have its own set of instance variables with unique values.
We can also declare instance variables inside instance methods by using the self
variable. If any instance variable is declared inside an instance method, that instance variable will be added to the object once we call that method.
# Define a class called Test
class Test:
def __init__(self):
self.a = 10
self.b = 20
def m1(self):
self.c = 30
# Create an instance of the Test class
t = Test()
# Call the m1 method on the instance t
t.m1()
# Print the dictionary representation of the instance t
print(t.__dict__)
Output:
{'a': 10, 'b': 20, 'c': 30}
Explanation:
We start by defining a class named Test
.
Inside the class, we have an initializer method __init__
. This method is automatically called when we create an instance of the class. In this method, we set two instance variables a
and b
, each initialized with values 10 and 20, respectively.
Next, we define an instance method called m1
. Instance methods take the self
parameter, allowing them to access and modify instance variables.
Inside the m1
method, we declare another instance variable c
and initialize it with the value 30.
Now, we create an instance of the Test
class and store it in the variable t
using the line t = Test()
.
After creating the instance, we call the m1
method on the instance t
using the line t.m1()
. This means that the m1
method is executed for the instance t
, which sets the instance variable c
to 30.
Finally, we print the dictionary representation of the instance t
using print(t.__dict__)
. In Python, every object has an attribute called __dict__
, which is a dictionary containing the instance variables and their corresponding values for that object.
The output shows the dictionary representation of the instance t
, which includes the instance variables a
, b
, and c
along with their respective values: {'a': 10, 'b': 20, 'c': 30}
.
This example illustrates how instance variables can be created and modified within instance methods using the self
variable, and they become part of the instance's dictionary once they are created.
We can also add instance variables outside of a class to a particular object.
# Define a class called Test
class Test:
def __init__(self):
self.a = 10
self.b = 20
def m1(self):
self.c = 30
# Create an instance of the Test class
t = Test()
# Call the m1 method on the instance t
t.m1()
# Add an instance variable 'd' to the instance t outside of the class
t.d = 40
# Print the dictionary representation of the instance t
print(t.__dict__)
Output:
{'a': 10, 'b': 20, 'c': 30, 'd': 40}
Explanation:
We start by defining a class named Test
.
Inside the class, we have an initializer method __init__
. This method is automatically called when we create an instance of the class. In this method, we set two instance variables a
and b
, each initialized with values 10 and 20, respectively.
Next, we define an instance method called m1
. Instance methods take the self
parameter, allowing them to access and modify instance variables.
Inside the m1
method, we declare another instance variable c
and initialize it with the value 30.
Now, we create an instance of the Test
class and store it in the variable t
using the line t = Test()
.
After creating the instance, we call the m1
method on the instance t
using the line t.m1()
. This means that the m1
method is executed for the instance t
, which sets the instance variable c
to 30.
Next, we add an instance variable d
to the instance t
outside of the class using the line t.d = 40
. This is an example of adding an instance variable to a particular object after the object is created. This new instance variable d
is specific to the object t
and is not shared with other instances of the Test
class.
Finally, we print the dictionary representation of the instance t
using print(t.__dict__)
. In Python, every object has an attribute called __dict__
, which is a dictionary containing the instance variables and their corresponding values for that object.
The output shows the dictionary representation of the instance t
, which includes the instance variables a
, b
, c
, and d
along with their respective values: {'a': 10, 'b': 20, 'c': 30, 'd': 40}
.
We can access instance variables within the class by using the self
variable and outside of the class by using the object reference.
# Define a class called Test
class Test:
def __init__(self):
self.a = 10
self.b = 20
def display(self):
print(self.a)
print(self.b)
# Create an instance of the Test class
t = Test()
# Call the display method to access instance variables within the class
t.display()
# Access instance variables outside the class using object reference
print(t.a, t.b)
Output:
10
20
10 20
Explanation:
We start by defining a class named Test
.
Inside the class, we have an initializer method __init__
. This method is automatically called when we create an instance of the class. In this method, we set two instance variables a
and b
, each initialized with values 10 and 20, respectively.
Now, we create an instance of the Test
class and store it in the variable t
using the line t = Test()
.
After creating the instance, we call the display
method on the instance t
using the line t.display()
. The display
method is defined within the class and internally accesses the instance variables a
and b
using the self
variable and then prints their values.
The output of t.display()
is 10
and 20
, which indicates that the method successfully accessed the instance variables within the class.
Next, we access the instance variables outside the class using the object reference t
. We use print(t.a, t.b)
to print the values of a
and b
, respectively.
The output of print(t.a, t.b)
is also 10
and 20
, which shows that we can access instance variables outside the class using the object reference as well.
In this example, we demonstrate how instance variables can be accessed both within and outside the class, highlighting the use of the self
variable inside the class and the object reference outside the class.
del self.variableName
del objectreference.variableName
Example 1: Deleting Instance Variables Within a Class
class Test:
def __init__(self):
self.a = 10
self.b = 20
self.c = 30
self.d = 40
def m1(self):
del self.d
t = Test()
print(t.__dict__) # Output: {'a': 10, 'b': 20, 'c': 30, 'd': 40}
t.m1()
print(t.__dict__) # Output: {'a': 10, 'b': 20, 'c': 30}
del t.c
print(t.__dict__) # Output: {'a': 10, 'b': 20}
Explanation:
Test
with an initializer method (__init__
) where we create four instance variables a
, b
, c
, and d
.m1
, which uses the del
statement to delete the instance variable d
.t
of the Test
class and initially, it contains all four instance variables.t.m1()
, the instance variable d
is deleted, as seen in the second print(t.__dict__)
.del t.c
to delete the instance variable c
, and it's not present in the third print(t.__dict__)
.Example 2: Deletion of Instance Variables in Different Objects
class Test:
def __init__(self):
self.a = 10
self.b = 20
self.c = 30
self.d = 40
t1 = Test()
t2 = Test()
del t1.a
print(t1.__dict__) # Output: {'b': 20, 'c': 30, 'd': 40}
print(t2.__dict__) # Output: {'a': 10, 'b': 20, 'c': 30, 'd': 40}
Explanation:
Test
with an initializer method (__init__
) where we create four instance variables a
, b
, c
, and d
.t1
and t2
of the Test
class.a
from t1
, but it doesn't affect t2
, as seen in the outputs of print(t1.__dict__)
and print(t2.__dict__)
.Example 3: Changing Instance Variable Values in Different Objects
class Test:
def __init__(self):
self.a = 10
self.b = 20
t1 = Test()
t1.a = 888
t1.b = 999
t2 = Test()
print('t1:', t1.a, t1.b) # Output: t1: 888 999
print('t2:', t2.a, t2.b) # Output: t2: 10 20
Explanation:
Test
with an initializer method (__init__
) where we create two instance variables a
and b
.t1
and t2
of the Test
class.a
and b
in t1
to 888
and 999
, respectively. However, these changes do not affect the values of the instance variables in t2
.