The isinstance() function is used to determine the type of an object, allowing us to check whether the object belongs to a specific type, such as an integer or string. The isinstance() function returns True if the specified object is of the specified type; otherwise, it returns False.
For example, if you want to check if an object is an integer, you can use the isinstance() function as follows:
def set_rating(self, rating):
if isinstance(rating, int) and 1 <= rating <= 5:
self._rating = rating
raise Exception("Invalid rating")
In this example, isinstance() is used to validate whether the rating argument is an integer within the range of 1 to 5.
Similarly, you can use isinstance() to verify if a variable is an instance of a specific class. Here's an example:
def set_customer(self, customer):
if isinstance(customer, Customer):
self._customer = customer
raise Exception("Invalid customer")
In this case, the isinstance() function is used to check if the customer argument is an instance of the Customer class.
By utilizing isinstance(), you can conditionally execute certain actions based on the type of an object. It is important to note that isinstance() is distinct from the modulo operator; the modulo operator calculates the remainder, while isinstance() checks if an object is an instance of a particular class.