หากคุณต้องการตรวจสอบว่าออบเจ็กต์ x เป็น instance ของ type ที่กำหนดพอดี (ไม่ใช่ subtype) คุณสามารถใช้ type เพื่อดึง type ของมันและตรวจสอบด้วยคำสั่ง is
ตัวอย่าง
x = "Hello"
if type(x) is str:
print("x is an instance of str")
ผลลัพธ์
x is an instance of str
หากคุณต้องการตรวจสอบว่า x เป็น instance ของ MyClass หรือ subclass ใดๆ ของ MyClass คุณสามารถใช้เมธอด isinstance ได้
ตัวอย่าง
x = "Hello"
if isinstance(x, str):
print("x is an instance of str")
ผลลัพธ์
x is an instance of str