Suppose I want to implement common variable among objects using class variables (similar to static in java/c++).
When I access class variable using object, it shows default value. Then I updaded class variable via object, its not updating class variable for other objects. It is showing old value in when class variable accessed via other objects or Class Name directly.
Why is it so, and what is the way in python to make class/static variable (common among objects)
# Class for Computer Science Student
class CSStudent:
stream = 'cse' # Class Variable
def __init__(self,name):
self.name = name # Instance Variable
# Objects of CSStudent class
a = CSStudent('Geek')
b = CSStudent('Nerd')
print(a.stream) # prints "cse"
print(b.stream) # prints "cse"
print(a.name) # prints "Geek"
print(b.name) # prints "Nerd"
# Class variables can be accessed using class
# name also
print(CSStudent.stream) # prints "cse"
# Now if we change the stream for just a it won't be changed for b
a.stream = 'ece'
b.stream = 'abc'
print(CSStudent.stream) # prints 'ece'
print(a.stream) # prints 'ece'
print(b.stream) # prints 'abc'