假设我想使用类变量在对象之间实现公共变量(类似于Java/c++中的静态变量).
当我使用Object访问类变量时,它显示缺省值. 然后我通过对象更新了类变量,它不更新其他对象的类变量. 当通过其他对象或类名直接访问类变量时,它在中显示旧值.
为什么会这样,以及在Python中使类/静态变量(对象通用)的方法是什么
# 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'