Instance variables

Instance variables refer to the data that are unique to instances (objects). Let's create an instance variable. We will write a new class2.py program:

class Leapx_org():
pass
L_obj1 = Leapx_org()
L_obj2 = Leapx_org()
L_obj1.f_name = "Mohit"
L_obj1.L_name = "RAJ"
L_obj1.pamount = "60000"
L_obj2.f_name = "Ravender"
L_obj2.L_name = "Dahiya"
L_obj2.pamount = "70000"
print L_obj1.f_name+ " "+ L_obj1.L_name
print L_obj2.f_name+ " "+ L_obj2.L_name

In the preceding code, L_obj1.f_name, L_obj1.L_name, and L_obj1.pamount are the instance variables, which are unique to the L_obj1 instance. Similarly, L_obj2.f_name, L_obj2.L_name, and L_obj2.pamount are the instance variables of the L_obj2 instance.

Let's run the code:

Output of code class2.py

If we create an instance variable, as shown in the code, then we would not get benefit of making a class. You can see repeatable code for both the instances. So we would not have to set the variable all the time. In order to make it automatically, we will use the special method __init__() function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.70.38