কম্পিউটার

delattr() এবং del() পাইথনে


এই দুটি ফাংশন ক্লাস থেকে বৈশিষ্ট্য অপসারণ করতে ব্যবহৃত হয়। delattr() অ্যাট্রিবিউট মুছে ফেলার ক্ষেত্রে 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.

উদাহরণ

নীচের উদাহরণে আমরা কাস্টক্লাস নামে একটি ক্লাস বিবেচনা করি। এটির বৈশিষ্ট্য হিসাবে গ্রাহকদের আইডি রয়েছে। পরবর্তীতে আমরা গ্রাহক নামে একটি অবজেক্ট হিসাবে ক্লাসটিকে ইনস্ট্যান্ট করি এবং এর অ্যাট্রিউটগুলি প্রিন্ট করি।

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'

ডেল() ব্যবহার করা

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'

  1. প্রোগ্রামারদের জন্য প্রয়োজনীয় পাইথন টিপস এবং কৌশল?

  2. পাইথন পুনরাবৃত্তিযোগ্য এবং পুনরাবৃত্তিকারীর মধ্যে পার্থক্য

  3. পাইথনে ==এবং অপারেটরের মধ্যে পার্থক্য।

  4. পাইথন ব্যতিক্রম বার্তা কিভাবে ক্যাপচার এবং প্রিন্ট করবেন?