Types of Variables

Published Aug. 3, 2023, 1:43 p.m.

Inside Python class, three types of variable are allowed:

  1. Instance Variables (Object Level Variables)
  2. Static Variables (Class Level Variables)
  3. Local Variables (Method Level Variables)

1. Instance Variables:

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.

Where we can declare Instance variables:

  1. Inside Constructor by using self variable
  2. Inside Instance Method by using self variable
  3. Outside of the class by using object reference variable

1. Inside Constructor by using self variable:

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:

  • We define a class Person with an __init__ method, which serves as the constructor for the class.
  • Inside the constructor, we declare three instance variables: name, age, and is_student, each initialized with specific values ('John', 30, and True).
  • We then create an object person1 of the Person class by calling the constructor Person().
  • After creating the object, we print its dictionary representation using person1.__dict__.
  • The output shows the dictionary containing the instance variables and their corresponding values for the object 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.

2. Inside Instance Method by using self variable:

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:

  1. We start by defining a class named Test.

  2. 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.

  3. Next, we define an instance method called m1. Instance methods take the self parameter, allowing them to access and modify instance variables.

  4. Inside the m1 method, we declare another instance variable c and initialize it with the value 30.

  5. Now, we create an instance of the Test class and store it in the variable t using the line t = Test().

  6. 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.

  7. 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.

  8. The output shows the dictionary representation of the instance t, which includes the instance variables ab, 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.

3. Outside of the class by using object reference variable:

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:

  1. We start by defining a class named Test.

  2. 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.

  3. Next, we define an instance method called m1. Instance methods take the self parameter, allowing them to access and modify instance variables.

  4. Inside the m1 method, we declare another instance variable c and initialize it with the value 30.

  5. Now, we create an instance of the Test class and store it in the variable t using the line t = Test().

  6. 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.

  7. 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.

  8. 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.

  9. The output shows the dictionary representation of the instance t, which includes the instance variables abc, and d along with their respective values: {'a': 10, 'b': 20, 'c': 30, 'd': 40}.

How to Access Instance Variables:

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:

  1. We start by defining a class named Test.

  2. 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.

  3. Now, we create an instance of the Test class and store it in the variable t using the line t = Test().

  4. 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.

  5. The output of t.display() is 10 and 20, which indicates that the method successfully accessed the instance variables within the class.

  6. 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.

  7. 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.

How to Delete Instance Variables from the Object:

1. Within a class, we can delete instance variables as follows:

del self.variableName

2. From outside of the class, we can delete instance variables as follows:

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:

  • We define a class named Test with an initializer method (__init__) where we create four instance variables abc, and d.
  • Inside the class, we have another method m1, which uses the del statement to delete the instance variable d.
  • We create an instance t of the Test class and initially, it contains all four instance variables.
  • After calling t.m1(), the instance variable d is deleted, as seen in the second print(t.__dict__).
  • Later, we use del t.c to delete the instance variable c, and it's not present in the third print(t.__dict__).

3. Note: The instance variables which are deleted from one object will not be deleted from other objects.

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:

  • We define a class named Test with an initializer method (__init__) where we create four instance variables abc, and d.
  • We create two instances t1 and t2 of the Test class.
  • We delete the instance variable a from t1, but it doesn't affect t2, as seen in the outputs of print(t1.__dict__) and print(t2.__dict__).

4. If we change the values of instance variables of one object, then those changes won't be reflected in the remaining objects, because for every object, we have a separate copy of instance variables available.

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:

  • We define a class named Test with an initializer method (__init__) where we create two instance variables a and b.
  • We create two instances t1 and t2 of the Test class.
  • We change the values of instance variables a and b in t1 to 888 and 999, respectively. However, these changes do not affect the values of the instance variables in t2.