在 Python 中修改类成员?


Python 面向对象编程允许在类级别或实例级别使用变量,其中变量只表示你在程序中使用的表示值的符号。 

在类级别,变量称为类变量,而在实例级别,变量称为实例变量。让我们通过一个简单的示例来理解类变量和实例变量 −

# Class Shark
class Shark:
animal_type= 'fish' # Class Variable
def __init__(self, name, age):
self.name = name
self.age = age

# Creating objects of Shark class
obj1 = Shark("Jeeva", 54)
obj2 = Shark("Roli", 45)

print ("Printing class variable using two instances")
print ("obj1.animal_type =", obj1.animal_type)
print ("obj2.animal_type =", obj2.animal_type)

#Let's change the class variable using instance variable
obj1.animal_type = "BigFish"

print ("\nPrinting class variable after making changes to one instance")
print ("obj1.animal_type=", obj1.animal_type)
print ("obj2.animal_type =", obj2.animal_type)

在上面的程序中,我们创建了一个 Shark 类,然后我们尝试使用对象更改类变量,这将为该特定对象创建一个新的实例变量,并且此变量会隐藏类变量。

输出

Printing class variable using two instances
obj1.animal_type = fish
obj2.animal_type = fish

Printing class variable after making changes to one instance
obj1.animal_type= BigFish
obj2.animal_type = fish

让我们修改我们的上述程序以获得正确的输出 −

# Class Shark
class Shark:
animal_type= 'fish' # Class Variable
def __init__(self, name, age):
self.name = name
self.age = age

# Creating objects of Shark class
obj1 = Shark("Jeeva", 54)
obj2 = Shark("Roli", 45)

print ("Printing class variable using two instances")
print ("obj1.animal_type =", obj1.animal_type)
print ("obj2.animal_type =", obj2.animal_type)

#Let's change the class variable using instance variable
#obj1.animal_type = "BigFish"

Shark.animal_type = "BigFish"
print("New class variable value is %s, changed through class itself" %(Shark.animal_type))

print ("\nPrinting class variable after making changes through instances")
print ("obj1.animal_type=", obj1.animal_type)
print ("obj2.animal_type =", obj2.animal_type)

结果

Printing class variable using two instances
obj1.animal_type = fish
obj2.animal_type = fish
New class variable value is BigFish, changed through class itself

Printing class variable after making changes through instances
obj1.animal_type= BigFish
obj2.animal_type = BigFish

更新日期:2019 年 7 月 30 日

513 次浏览

开启您的 职业生涯

完成课程以获取认证

开始
广告