Monday, March 15, 2021

Types of Variables in Python ( related to Classes and Objects in OOPS )

 


Types of Variables in Python

 

* The variables which are written inside a class are of primarily two types :

1) Instance Variables

2) Class Variables / Static Variables

 

* Instance variables are the variables whose separate copy is created in every instance ( or object )

 

* For example , if 'x' is an instance variable and if we create 2 instance variables then there will be 2 copies of 'x' in the instances .

 

* When we modify the copy of 'x' in any instance, then it will not modify the other two copies .

 

==========================================
Python Program to understand Instance Variables
==========================================

 

# instance variable example

Class Sample:

    # this is a constructor

    def __init__(self):

    self.x = 10

 

    # this is an instance method

   def modify(self):

   self.x += 1

 

 

# Create 2 instances

    s1 = Sample()

    s2 = Sample()

    print(' x in s1 = ', s1.x)

    print(' x in s2 = ', s2.x)

 

# modify x in s1

     s1.modify()

    print(' x in s1 = ' , s1.x)

    print(' x in s2 = ' , s2.x)

 

# modify x in s1

    s1.modify()

    print(' x in s1 = ', s1.x)

    print(' x in s2 = ', s2.x)

 

Output

x in s1 = 10

x in s2 = 10

x in s1 = 11

x in s2 = 10

================================================================

 

* Instance Variables are defined and initialised using a constructor with 'self' parameter . In the above program it can be realised in the line just after the usage of the docstring over where the code for declaration and definition of the Instance Variables is mentioned and in the succeeding line the __init__(self) is defined .

 

* In order to access the instance variables one needs Instance methods with 'self' as the first parameter which can be observed from the above code as well

 

* It is possible that the instance methods may have other parameters in addition to the 'self' parameter .

 

* In order to access the instance variables , one can use a self.variable in a program .

 

* It is also possible to access the instance variables from outside the class as : instancename.variable e.g. s1.x .

 

* Unlike instance variables , class variables are the variables whose single copy is available to all the instances of the class .

 

No comments:

Post a Comment