更改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类,然后尝试使用object更改class变量,这将为该特定对象创建一个新的实例变量,并且此变量遮盖了class变量。
输出
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