ฟังก์ชันทั้งสองนี้ใช้สำหรับลบแอตทริบิวต์ออกจากคลาส ฟังก์ชัน delattr() อนุญาตให้ลบแอตทริบิวต์แบบไดนามิก ในขณะที่ del() ใช้ลบแอตทริบิวต์อย่างชัดเจนและมีประสิทธิภาพมากกว่า
การใช้งาน delattr()
ไวยากรณ์: delattr(object_name, attribute_name) โดย object_name คือชื่อของออบเจ็กต์ที่สร้างจากคลาส attribute_name คือชื่อแอตทริบิวต์ที่ต้องการลบ
ตัวอย่าง
ในตัวอย่างด้านล่าง เราพิจารณาคลาสชื่อ custclass ซึ่งมีแอตทริบิวต์เป็นรหัสลูกค้า จากนั้นเราสร้างออบเจ็กต์ชื่อ customer และพิมพ์แอตทริบิวต์ต่างๆ
class custclass:
custid1 = 0
custid2 = 1
custid3 = 2
customer = custclass()
print(customer.custid1)
print(customer.custid2)
print(customer.custid3)
ผลลัพธ์
การรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้ -
0 1 2
ตัวอย่างการใช้ delattr()
ในขั้นตอนต่อไป เรารันโปรแกรมอีกครั้งโดยใช้ฟังก์ชัน delattr() ครั้งนี้เมื่อเราพยายามพิมพ์ custid3 จะเกิดข้อผิดพลาด เนื่องจากแอตทริบิวต์ถูกลบออกจากคลาสแล้ว
class custclass:
custid1 = 0
custid2 = 1
custid3 = 2
customer = custclass()
print(customer.custid1)
print(customer.custid2)
delattr(custclass, 'custid3')
print(customer.custid3)
ผลลัพธ์
การรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้ -
0
1
Traceback (most recent call last):
File "xxx.py", line 13, in
print(customer.custid3)
AttributeError: 'custclass' object has no attribute 'custid3'
การใช้งาน del()
ไวยากรณ์: del(object_name.attribute_name) โดย object_name คือชื่อของออบเจ็กต์ที่สร้างจากคลาส attribute_name คือชื่อแอตทริบิวต์ที่ต้องการลบ
ตัวอย่าง
เราทำซ้ำตัวอย่างข้างต้นด้วยฟังก์ชัน del() โปรดสังเกตว่ามีความแตกต่างในไวยากรณ์จาก delattr()
class custclass:
custid1 = 0
custid2 = 1
custid3 = 2
customer = custclass()
print(customer.custid1)
print(customer.custid2)
del(custclass.custid3)
print(customer.custid3)
ผลลัพธ์
การรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้ -
0
1
Traceback (most recent call last):
File "xxx.py", line 13, in
print(customer.custid3)
AttributeError: 'custclass' object has no attribute 'custid3'