কম্পিউটার টিউটোরিয়াল

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


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

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'
  1. প্রোগ্রামারদের জন্য অপরিহার্য পাইথন টিপস এবং ট্রিকস

  2. পাইথনে ইটেরেবল (Iterable) এবং ইটেরেটর (Iterator) এর পার্থক্য

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

  4. পাইথন এক্সসেপশন মেসেজ ক্যাপচার ও প্রিন্ট করা