ในบทความนี้ เราจะเรียนรู้เกี่ยวกับฟังก์ชัน isinstance() และ type() ที่มีใน Python 3.x หรือเวอร์ชันก่อนหน้า เมธอดเหล่านี้พื้นฐานแล้วใช้เพื่อตรวจสอบ reference และลักษณะของ entities
เมธอด isinstance()
Syntax
isinstance(object_entity, comparison_equivalent)
Return Value − True ถ้า object_entity ตรงกับ comparison_equivalent
ตอนนี้มาดูว่าเมธอด isinstance() ทำงานอย่างไร
ตัวอย่าง
class Test:
var = 786
TestInstance = Test()
print(isinstance(TestInstance, Test))
print(isinstance(TestInstance, (list, tuple)))
print(isinstance(TestInstance, (list, tuple, Test)))
ผลลัพธ์
True False True
บรรทัดแรกและสามแสดง True เพราะ reference ของ Test และ TestInstance ตรงกัน ในขณะที่บรรทัดที่สองแสดง False เนื่องจาก reference ของ TestInstance ไม่ตรงกับ list และ tuple references
มาดูตัวอย่างอีกอันเพื่อเข้าใจดีขึ้น
ตัวอย่าง
Test = [1, 2, 3] result = isinstance(Test, list) print(Test, 'list:', result) result = isinstance(Test, dict) print(Test, 'dict:', result) result = isinstance(Test, (dict, list)) print(Test, 'dict or list:', result)
ผลลัพธ์
[1, 2, 3] list: True [1, 2, 3] dict: False [1, 2, 3] dict or list: True
ที่นี่เมื่อ Test ตรงกับ list instance จะแสดง True บนหน้าจอ False ถ้าไม่ตรง
เมธอด type()
Syntax
type(entity)
Return Value − ชนิดของ entity ที่ส่งผ่านเป็นอาร์กิวเมนต์
ตอนนี้มาดูว่าเมธอด type() ทำงานอย่างไร
ตัวอย่าง
Dictinp = {1: 'Tutorial', 2: 'Point'}
print(type(Dictinp))
Listinp = ['t', 'u', 't']
print(type(Listinp))
Tupleinp = ('Tut', 'orial', 'Point')
print(type(Tupleinp))
ผลลัพธ์
<class 'dict'> <class 'list'> <class 'tuple'>
ที่นี่ผลลัพธ์มีชนิดที่เกี่ยวข้องของ entity ที่ส่งผ่านระหว่างการเรียกเมธอด ชนิดนี้ยังสามารถใช้ในการเปรียบเทียบและคำสั่งเงื่อนไขอื่นๆ ได้
ตอนนี้มาดูตัวอย่างบนคำสั่งเงื่อนไข
ตัวอย่าง
Listinp = ['t', 'u', 't']
Tupleinp = ('Tut', 'orial', 'Point')
if type(Listinp) is not type(Tupleinp):
print("Type mismatch")
else:
print("Type match")
ผลลัพธ์
Type Mismatch
Type mismatch ถูกแสดง เพราะ list และ tuple เป็นชนิดข้อมูลที่ต่างกัน
สรุป
ในบทความนี้ เราได้เรียนรู้การนำ type() และ isinstance() method ไปใช้งานใน Python 3.x หรือเวอร์ชันก่อนหน้า