isinstance()

hequamily

hequamily

Posted on June 9, 2023

isinstance()

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
else:
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
else:
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.

💖 💪 🙅 🚩
hequamily
hequamily

Posted on June 9, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024