isinstance function
Detailed introduction
isinstance
is 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,isinstance
Will 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 useisinstance
to 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,isinstance
Used for inspectionobj
Is it trueint
orstr
type.
hasattr function
Detailed introduction
hasattr
is 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,hasattr
Will 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,hasattr
Used for inspectionperson
Does the instance havename
、age
andaddress
Attributes. becauseaddress
The attribute does not exist, so the corresponding onehasattr
Calling returnsFalse
。
usehasattr
It can avoid causing a non-existent property when trying to accessAttributeError
Exception, 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!