在Python中更改类成员
在前面的事实中,我们已经看到Python没有 static 关键字。在类声明中赋值的所有变量都是类变量。
在更改类变量的值时我们应该小心。如果我们尝试使用对象更改类变量,则会为该特定对象创建一个新的实例(或非静态)变量,并且该变量会隐藏类变量。下面是一个演示相同的Python程序。
Python3
# Class for Computer Science Student
class CSStudent:
stream = 'cse' # Class Variable
def __init__(self, name, roll):
self.name = name
self.roll = roll
# Driver program to test the functionality
# Creating objects of CSStudent class
a = CSStudent("Geek", 1)
b = CSStudent("Nerd", 2)
print ("Initially")
print ("a.stream =", a.stream )
print ("b.stream =", b.stream )
# This thing doesn't change class(static) variable
# Instead creates instance variable for the object
# 'a' that shadows class member.
a.stream = "ece"
print ("\nAfter changing a.stream")
print ("a.stream =", a.stream )
print ("b.stream =", b.stream )
Python3
# Program to show how to make changes to the
# class variable in Python
# Class for Computer Science Student
class CSStudent:
stream = 'cse' # Class Variable
def __init__(self, name, roll):
self.name = name
self.roll = roll
# New object for further implementation
a = CSStudent("check", 3)
print "a.stream =", a.stream
# Correct way to change the value of class variable
CSStudent.stream = "mec"
print "\nClass variable changes to mec"
# New object for further implementation
b = CSStudent("carter", 4)
print "\nValue of variable steam for each object"
print "a.stream =", a.stream
print "b.stream =", b.stream
输出:
Initially
a.stream = cse
b.stream = cse
After changing a.stream
a.stream = ece
b.stream = cse
我们应该只使用类名来改变类变量。
Python3
# Program to show how to make changes to the
# class variable in Python
# Class for Computer Science Student
class CSStudent:
stream = 'cse' # Class Variable
def __init__(self, name, roll):
self.name = name
self.roll = roll
# New object for further implementation
a = CSStudent("check", 3)
print "a.stream =", a.stream
# Correct way to change the value of class variable
CSStudent.stream = "mec"
print "\nClass variable changes to mec"
# New object for further implementation
b = CSStudent("carter", 4)
print "\nValue of variable steam for each object"
print "a.stream =", a.stream
print "b.stream =", b.stream
输出:
a.stream = cse
Class variable changes to mec
Value of variable steam for each object
a.stream = mec
b.stream = mec