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