পাইথনে টাইপ চেক করার দুটি মূল উপায় রয়েছে, যাদের ব্যবহার ক্ষেত্র আলাদা।
১. সঠিক টাইপ চেক (Exact Type) — type(x) is Type
x = "Hello"
if type(x) is str:
print("x is an instance of str")
আউটপুট
x is an instance of str
ব্যবহার: সাবক্লাস এক্সক্লুড করতে চাইলে (খুব র্যার)।
২. ইনস্ট্যান্স চেক (সাবক্লাস সহ) — isinstance(x, Type)
x = "Hello"
if isinstance(x, str):
print("x is an instance of str")
আউটপুট
x is an instance of str
ব্যবহার: সাধারণ প্রোগ্রামিংয়ের জন্য সর্বোত্তম। সাবক্লাসও ভ্যালিড মনে করে (Liskov Substitution Principle)।
তুলনা
class Base: pass class Derived(Base): pass d = Derived() type(d) is Base # False (Exact match) isinstance(d, Base) # True (Subclass OK)
সুপারিশ
- প্রায়ইশ্ব
isinstance()ব্যবহার করুন type() isশুধু খুব নির্দিষ্ট কেসে (মেটাপ্রোগ্রামিং, সিঙ্গেলটন চেক)- ডক টাইপিং (duck typing) প্রিয়:
hasattr(obj, 'method')বা EAFP (try/except)