Site icon infometadata.com

Types of Variables

PYTHON OOPS: Types of Variables:

In python we can have two types of variables inside class:

Now Lets understands both the types of variables what exactly they are:

Instance variables are the variable which are written inside the methods of the class, the separate copy of instance variable is created for each instance.

For example if variable name is instance variable and if three instances created there will be three copies of instance variable will be created. If one instance modifies the value of instance variable, it will not modify the value for other instance’s variable.

Program to understand instance variable:

class InstanceExample:

def __init__(self):
self.x = 10;

def modifyInstanceVariable(self):
self.x += 1

obj1 = InstanceExample()
obj2 = InstanceExample()
obj3 = InstanceExample()

obj3.modifyInstanceVariable()

print('x in obj1 = ', obj1.x)
print('x in obj2 = ', obj2.x)
print('x in obj3 = ', obj3.x)

Above program will produce output like:
x in obj1 = 10
x in obj2 = 10
x in obj3 = 11

As you can see when value of instance variable modified by object obj3 so it is modified for obj3 only, other two copies of instance variables are unchanged.

The variables which are written inside class but outside methods are called class variables or static variables.
Unlike instance variables, class variables are the variables whose single copy is available to all the instances of a class, if class variable’s value modified by any instance of the class it will be modified for all the instances of the class.


class InstanceExample:

x = 10

@classmethod
def modifyInstanceVariable(cls):
cls.x += 1

obj1 = InstanceExample()
obj2 = InstanceExample()
obj3 = InstanceExample()

obj3.modifyInstanceVariable()

print('x in obj1 = ', obj1.x)
print('x in obj2 = ', obj2.x)
print('x in obj3 = ', obj3.x)


class InstanceExample:

x = 10

InstanceExample.x += 1

obj1 = InstanceExample()
obj2 = InstanceExample()
obj3 = InstanceExample()

print('x in obj1 = ', obj1.x)
print('x in obj2 = ', obj2.x)
print('x in obj3 = ', obj3.x)

Above tow programs will produce output like:

x in obj1 = 11
x in obj2 = 11
x in obj3 = 11

As you can see when one of the instance changes value of class variable or static variable it get changed for all the available instances.

Exit mobile version