Python中的类或静态变量

所有对象共享类或静态变量。实例或非静态变量对于不同的对象是不同的(每个对象都有一个副本)。例如,让计算机科学学生以班级为代表 CSStudent .对于所有对象,该类可能有一个静态变量,其值为“cse”。类也可能有非静态成员,比如 名称 在里面 C++ JAVA ,我们可以使用静态关键字使变量成为类变量。没有前面静态关键字的变量是实例变量。看见 对于Java示例和 对于C++的例子。 这个 python 方法简单;它不需要静态关键字。

null

在中指定值的所有变量 这个 类声明是类变量。和变量 那个 方法中的赋值是实例变量。

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'


输出:

csecseGeekNerd12cseececseecemech

本文由 哈希特·古普塔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以写一篇文章,然后将文章邮寄给评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享