เมื่อเราสร้างอินสแตนซ์ของคลาสใน Python ตัวแปรและฟังก์ชันทั้งหมดจะได้รับการสืบทอดไปยังคลาสที่สร้างอินสแตนซ์ใหม่ แต่อาจมีบางครั้งที่เราไม่ต้องการให้ตัวแปรบางตัวของคลาสพาเรนต์สืบทอดโดยคลาสย่อย ในบทความนี้ เราจะสำรวจสองวิธีในการทำเช่นนั้น
ตัวอย่างตัวอย่าง
ในตัวอย่างด้านล่าง เราแสดงให้เห็นว่าตัวแปรได้รับความร้อนจากคลาสที่กำหนดอย่างไร และมีการใช้ตัวแปรร่วมกันอย่างไรในคลาสที่สร้างอินสแตนซ์ทั้งหมด
class MyClass:
listA= []
# Instantiate Both the classes
x = MyClass()
y = MyClass()
# Manipulate both the classes
x.listA.append(10)
y.listA.append(20)
x.listA.append(30)
y.listA.append(40)
# Print Results
print("Instance X: ",x.listA)
print("Instance Y: ",y.listA) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
Instance X: [10, 20, 30, 40] Instance Y: [10, 20, 30, 40]
ตัวแปรไพรเวทคลาสพร้อม __inti__
เราสามารถใช้เมธอด I need a เพื่อทำให้ตัวแปรภายในคลาสเป็นแบบไพรเวต ตัวแปรเหล่านี้จะไม่ถูกแชร์ในคลาสต่างๆ เมื่อคลาสพาเรนต์ถูกสร้างขึ้น
ตัวอย่าง
class MyClass:
def __init__(self):
self.listA = []
# Instantiate Both the classes
x = MyClass()
y = MyClass()
# Manipulate both the classes
x.listA.append(10)
y.listA.append(20)
x.listA.append(30)
y.listA.append(40)
# Print Results
print("Instance X: ",x.listA)
print("Instance Y: ",y.listA) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
Instance X: [10, 30] Instance Y: [20, 40]
โดยการประกาศตัวแปรภายนอก
ในแนวทางนี้ เราจะประกาศตัวแปรนอกคลาสอีกครั้ง เมื่อตัวแปรได้รับการเตรียมใช้งานอีกครั้งซึ่งจะไม่ถูกแชร์ในคลาสที่สร้างอินสแตนซ์
ตัวอย่าง
class MyClass:
listA = []
# Instantiate Both the classes
x = MyClass()
y = MyClass()
x.listA = []
y.listA = []
# Manipulate both the classes
x.listA.append(10)
y.listA.append(20)
x.listA.append(30)
y.listA.append(40)
# Print Results
print("Instance X: ",x.listA)
print("Instance Y: ",y.listA)
Output ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
Instance X: [10, 30] Instance Y: [20, 40]