এই টিউটোরিয়ালে আমরা পাইথনে self কিওয়ার্ড সম্পর্কে শিখব।
নোট: self পাইথনে কিওয়ার্ড নয়।
ক্লাসে self ব্যবহার করে ইনস্ট্যান্সের প্রপার্টি এক্সেস করা হয়। প্রতিটি ইনস্ট্যান্সের আলাদা ভ্যালু থাকে।
class Laptop:
def __init__(self, company, model):
self.company = company
self.model = model
laptop_one = Laptop('Lenovo', 'ideapad320')
laptop_two = Laptop('Dell', 'inspiron 7000')
print(laptop_one.company) # Lenovo
print(laptop_two.company) # Dell
পাইথন অটোমেটিক্যালি ইনস্ট্যান্সের রেফারেন্স পাস করে মেথড কল করার সময়। self সেই রেফারেন্স ক্যাপচার করে। নাম পরিবর্তন করা যায় (বেস্ট প্র্যাকটিস self)।
class Laptop:
def __init__(other_than_self, company, model, colors):
other_than_self.company = company
other_than_self.model = model
other_than_self.colors_available = colors
def is_laptop_available(not_self_but_still_self, color):
return color in not_self_but_still_self.colors_available
laptop = Laptop('Dell', 'inspiron 7000', ['Silver', 'Black'])
print(laptop.is_laptop_available('Silver')) # True
print(laptop.is_laptop_available('White')) # False
True False
self কিওয়ার্ড নয়, কনভেনশন। এটি ইনস্ট্যান্স রেফারেন্স ধারণ করে। বেস্ট প্র্যাকটিস: self নামই ব্যবহার করুন।