Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách chuẩn kiểm tra type trong Python

Kiểm tra exact type (không kể subclass): type(x) is SomeType.

x = "Hello"
if type(x) is str:
    print("x is an instance of str")

Kiểm tra instance của class hoặc subclass: isinstance(x, SomeType).

if isinstance(x, str):
    print("x is an instance of str")

Best practice: Ưu tiên isinstance cho polymorphism, type() is chỉ khi cần exact type.