Changing Class Members in Python

Python Methods and Functions

We have to be careful when changing the value of a class variable . If we try to change a class variable using an object, a new instance (or non-static) variable is created for that particular object and that variable shadows the class variables. Below is a Python program that demonstrates the same.

# Class for computer science students

class CSStudent:

  stream = 'cse'   # Class variable

def __ init __ ( self , name, roll):

  self . name = name 

self . roll = roll

  
# The driver of the program for checking the functionality
# Creating objects of the CSStudent class

a = CSStudent ( "Geek" , 1 )

b = CSStudent ( "Nerd" , 2 )

 

print " Initially "

print "a.stream =" , a.stream

print "b.stream =" , b.stream 

 
# This thing does not change the class (static) variable
# Creates an instance variable for the object instead
# & # 39; a & # 39; which hides the class member.

a. stream = "ece"

 

print "After changing a.stream"

print "a.stream =" , a.stream

print "b.stream =" , b.stream

Output:

 Initially a.stream = cse b .stream = cse After changing a. stream a.stream = ece b.stream = cse 

We have to change the class variables using only the class name.

# Program to show how to make changes to the
# class variable in Python

 
# Class for Computer Science Student

class CSStudent:

  stream = 'cse'   # Class Variable 

  def __init __ (self, name, roll):

  self.name = name 

  self.roll = roll

 
# New object for further implementation

a = CSStudent ( "check" , 3)

print "a.tream =" , a.stream

 
# Correct way to change the value of class variable

CSStudent.stream = "mec"

print "Class variable changes to mec"

 
# New object for further implementation

b = CSStudent ( "carter" , 4)

  

print " Value of variable steam for each object "

print "a.stream =" , a.stream

print "b.stream =" , b.stream

Output:

 a.tream = cse Class variable changes to mec Value of variable steam for each object a.stream = mec b.stream = mec 

This article courtesy of Nikhil Kumar Singh . If you like Python.Engineering and would like to contribute, you can also write an article and mail it to [email protected] See your article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you'd like to share more information on the topic under discussion





Tutorials