Python中的类或静态变量
所有对象共享类或静态变量。不同对象的实例或非静态变量是不同的(每个对象都有一个副本)。例如,让一个计算机科学专业的学生由CSStudent类表示。该类可能有一个静态变量,其值为所有对象的“cse”。并且类也可能有非静态成员,如name和roll 。在 C++ 和Java中,我们可以使用 static 关键字使变量成为类变量。前面没有 static 关键字的变量是实例变量。有关Java示例,请参见 this,对于 C++ 示例,请参见 this。
Python方法很简单;它不需要静态关键字。
All variables which are assigned a value in the class declaration are class variables. And variables that are assigned values inside methods are instance variables.
Python
# Python program to show that the variables with a value
# assigned in class declaration, are class variables
# Class for Computer Science Student
class CSStudent:
stream = 'cse' # Class Variable
def __init__(self,name,roll):
self.name = name # Instance Variable
self.roll = roll # Instance Variable
# Objects of CSStudent class
a = CSStudent('Geek', 1)
b = CSStudent('Nerd', 2)
print(a.stream) # prints "cse"
print(b.stream) # prints "cse"
print(a.name) # prints "Geek"
print(b.name) # prints "Nerd"
print(a.roll) # prints "1"
print(b.roll) # prints "2"
# 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'
print(a.stream) # prints 'ece'
print(b.stream) # prints 'cse'
# To change the stream for all instances of the class we can change it
# directly from the class
CSStudent.stream = 'mech'
print(a.stream) # prints 'ece'
print(b.stream) # prints 'mech'
输出:
cse
cse
Geek
Nerd
1
2
cse
ece
cse
ece
mech