ये दोनों फ़ंक्शन क्लासेस से एट्रिब्यूट हटाने के लिए उपयोग किए जाते हैं। 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() फ़ंक्शन लागू करके फिर से प्रोग्राम चलाते हैं। इस बार जब हम 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):
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'