การเขียนโปรแกรมเชิงวัตถุ 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