SoFunction
Updated on 2025-03-04

Implementation example of isinstance and hasattr in Python

isinstance function

Detailed introduction

isinstanceis a built-in function in Python that determines whether an object is a known type or a subclass of that type (for class types). This function accepts two parameters: the first parameter is the object you want to check, and the second parameter is a type or tuple of type. If the first parameter is an instance of the type specified by the second parameter or its subclass,isinstanceWill returnTrue, otherwise returnFalse

This function is very useful because it allows you to check the type of an object at runtime, allowing you to write more general and robust code.

Application examples and code examples

Suppose you have a function that takes an argument and prints out the type of that argument. However, you only want to handle parameters of integer and string type. You can useisinstanceto check the types of parameters and process them accordingly.

def print_type(obj):
    if isinstance(obj, int):
        print(f"{obj} is an integer.")
    elif isinstance(obj, str):
        print(f"{obj} is a string.")
    else:
        print(f"Unsupported type: {type(obj)}")

# testprint_type(42)        # Output: 42 is an integer.print_type("hello")   # Output: hello is a string.print_type([1, 2, 3]) # Output: Unsupported type: <class 'list'>

In this example,isinstanceUsed for inspectionobjIs it trueintorstrtype.

hasattr function

Detailed introduction

hasattris another built-in function in Python that checks whether an object has specified properties. This function accepts two parameters: the first parameter is the object you want to check, and the second parameter is a string that indicates the name of the property you want to check. If the object has this property,hasattrWill returnTrue, otherwise returnFalse

This function is very useful when dealing with dynamic properties or not sure whether an object has a certain property.

Application examples and code examples

Suppose you have a class that has some properties, and you want to check whether an instance has a specific property at runtime.

class Person:
    def __init__(self, name, age=None):
         = name
         = age

# Create a Person instanceperson = Person("Alice")

# Check propertiesprint(hasattr(person, "name"))   # Output: Trueprint(hasattr(person, "age"))    # Output: Trueprint(hasattr(person, "address"))# Output: False
# AttributeError will be raised if you try to access the non-existent attribute (not recommended)# print()

# Safer accessif hasattr(person, "address"):
    print()
else:
    print("Address is not available.")

In this example,hasattrUsed for inspectionpersonDoes the instance havenameageandaddressAttributes. becauseaddressThe attribute does not exist, so the corresponding onehasattrCalling returnsFalse

usehasattrIt can avoid causing a non-existent property when trying to accessAttributeErrorException, thus making the code more robust.

This is the article about the implementation examples of isinstance and hasattr in Python. For more related Python isinstance and hasattr content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!