In the previous fact, we have seen that Python doesn’t have the static keyword. All variables that are assigned a value in the class declaration are class variables.
We should 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 for that particular object is created and this variable shadows the class variables. Below is a Python program to demonstrate the same.
Python3
class CSStudent:
stream = 'cse'
def __init__(self, name, roll):
self.name = name
self.roll = roll
a = CSStudent("Geek", 1)
b = CSStudent("Nerd", 2)
print ("Initially")
print ("a.stream =", a.stream )
print ("b.stream =", b.stream )
a.stream = "ece"
print ("\nAfter 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 should change class variables using class names only.
Python3
class CSStudent:
stream = 'cse'
def __init__(self, name, roll):
self.name = name
self.roll = roll
a = CSStudent("check", 3)
print "a.stream =", a.stream
CSStudent.stream = "mec"
print "\nClass variable changes to mec"
b = CSStudent("carter", 4)
print "\nValue of variable steam for each object"
print "a.stream =", a.stream
print "b.stream =", b.stream
|
Output:
a.stream = cse
Class variable changes to mec
Value of variable steam for each object
a.stream = mec
b.stream = mec
If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills, become a part of the hottest trend in the 21st century.Dive into the future of technology - explore the
Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
14 Dec, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...