Changing Class Members in Python?

PythonServer Side ProgrammingProgramming

Python object oriented programming allows variables to be used at the class level or the instance level where variables are simply the symbols denoting value you’re using in the program. 

At the class level, variables are referred to as class variables whereas variables at the instance level are referred to as instance variables. Let’s understand the class variable and instance variable through a simple example −

# Class Shark
class Shark:
animal_type= 'fish' # Class Variable
def __init__(self, name, age):
self.name = name
self.age = age

# Creating objects of Shark class
obj1 = Shark("Jeeva", 54)
obj2 = Shark("Roli", 45)

print ("Printing class variable using two instances")
print ("obj1.animal_type =", obj1.animal_type)
print ("obj2.animal_type =", obj2.animal_type)

#Let's change the class variable using instance variable
obj1.animal_type = "BigFish"

print ("\nPrinting class variable after making changes to one instance")
print ("obj1.animal_type=", obj1.animal_type)
print ("obj2.animal_type =", obj2.animal_type)

In above program, we have created a Shark class and then we are trying to change the class variable using object, this will create a new instance variable for that particular object and this variable shadows the class variable.

output

Printing class variable using two instances
obj1.animal_type = fish
obj2.animal_type = fish

Printing class variable after making changes to one instance
obj1.animal_type= BigFish
obj2.animal_type = fish

Let’s modify our above program so as to get the correct output −

# Class Shark
class Shark:
animal_type= 'fish' # Class Variable
def __init__(self, name, age):
self.name = name
self.age = age

# Creating objects of Shark class
obj1 = Shark("Jeeva", 54)
obj2 = Shark("Roli", 45)

print ("Printing class variable using two instances")
print ("obj1.animal_type =", obj1.animal_type)
print ("obj2.animal_type =", obj2.animal_type)

#Let's change the class variable using instance variable
#obj1.animal_type = "BigFish"

Shark.animal_type = "BigFish"
print("New class variable value is %s, changed through class itself" %(Shark.animal_type))

print ("\nPrinting class variable after making changes through instances")
print ("obj1.animal_type=", obj1.animal_type)
print ("obj2.animal_type =", obj2.animal_type)

Result

Printing class variable using two instances
obj1.animal_type = fish
obj2.animal_type = fish
New class variable value is BigFish, changed through class itself

Printing class variable after making changes through instances
obj1.animal_type= BigFish
obj2.animal_type = BigFish
raja
Published on 02-May-2019 11:45:17
Advertisements