热线电话:13121318867

登录
2019-02-23 阅读量: 732
python中类与静态变量有什么不同

类或静态变量由所有对象共享。对于不同的对象,实例或非静态变量是不同的(每个对象都有一个副本)。

例如,让计算机科学专业的学生由CSStudent代表。该类可以有一个静态变量,其值为所有对象的“cse”。类也可能有非静态成员,如name和roll。

C ++Java中,我们可以使用static关键字将变量作为类变量。没有前面的static关键字的变量是实例变量。见对Java的例子,对C ++的例子。

在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"

0.0000
4
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子