Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

delattr() และ del() ใน Python


ฟังก์ชันทั้งสองนี้ใช้เพื่อลบแอตทริบิวต์ออกจากคลาส delattr() อนุญาตให้ dynamoc ลบแอตทริบิวต์ในขณะที่ del() มีประสิทธิภาพมากขึ้นในการลบแอตทริบิวต์อย่างชัดเจน

การใช้ delattr()

Syntax: delattr(object_name, attribute_name)
Where object name is the name of the object, instantiated form the class.
Attribute_name is the name of the attribute to be deleted.

ตัวอย่าง

ในตัวอย่างด้านล่าง เราพิจารณาคลาสชื่อ 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() ครั้งนี้เมื่อเราต้องการพิมพ์ id3 เราได้รับข้อผิดพลาดเนื่องจากแอตทริบิวต์ถูกลบออกจากคลาส

class custclass:
   custid1 = 0
   custid2 = 1
   custid3 = 2
customer=custclass()
print(customer.custid1)
print(customer.custid2)
delattr(custclass,'custid3')
print(customer.custid3)

ผลลัพธ์

การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -

0
Traceback (most recent call last):
1
File "xxx.py", line 13, in print(customer.custid3)
AttributeError: 'custclass' object has no attribute 'custid3'

การใช้ del()

Syntax: del(object_name.attribute_name)
Where object name is the name of the object, instantiated form the class.
Attribute_name is the name of the attribute to be deleted.

ตัวอย่าง

เราทำซ้ำตัวอย่างข้างต้นด้วยฟังก์ชัน 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'