Can we create any number of reference variables for an object?

Yes, An object in the memory can be pointed by any number of reference variables as shown in the below example.

example:

class Student:
    def __init__(self):
        self.name = "Ramu"
        self.age = 34
        self.color = "White"

#creating object of class Student and reference variable s_1.        
s_1 = Student()

print()
print(s_1.name)
print()
print(s_1.age)
print()
print(s_1.color)
print()


#Creating another reference variable.
s_2 = s_1

print()
print(s_2.name)
print()
print(s_2.age)
print()
print(s_2.color)
print()

#Creating another reference variable.
s_3 = s_1

print()
print(s_3.name)
print()
print(s_3.age)
print()
print(s_3.color)
print()

#check whether s_2 is pointing at the same memory location where 
#s_1 is pointing.
print(s_2 is s_1) #True
print()

print(id(s_2) == id(s_1)) #True
Output:

Ramu

34

White


Ramu

34

White


Ramu

34

White

True

True

In the above example, you can see we are creating the reference variable “s_1” that contains the address(memory location) of an object of the “Student” class. We are now assigning a value of s_1 to s_2 (s_2 = s_1) as we know the assignment operator works from right to left, which means the value of s_1 is copied to value s_2. similarly, s_3 to s_1. So when we are assigning s_2 to s_1, in this case, the Python memory manager will not create any new object in the memory rather than it will point to the same location. The below diagram will give a better understanding.

s_1 is pointing at memory location 1000.
when a new reference variable s_2 is created. It starts pointing to the same memory location, meaning no new object is being created similarly for s_3.

Contributed by – Devanshu Kumar

Contribute your article – contribute.articles@tech-bloggers.in

Leave a Comment

Your email address will not be published. Required fields are marked *

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock