Python isinstance() Built in Function

The isinstance() function checks whether an object is an instance of a specified class or type. It returns True if the object belongs to the class or type, otherwise False.

Here are some examples of using the isinstance() function:

# Example 1: Check for built-in types
mystr = "Hello World"
num = 100
flt = 10.2
print(isinstance(mystr, str))
# True
print(isinstance(mystr, int)) # False
print(isinstance(num, int)) # True
print(isinstance(num, str)) # False
print(isinstance(flt, float)) # True
print(isinstance(flt, int)) # False


# Example 2: Check for multiple types using a tuple
mylist = [1, 2, 3]
mytuple = (4, 5, 6)
myset = {7, 8 ,9}

print(isinstance(mylist, (list, tuple))) # True
print(isinstance(mytuple, (list, tuple))) # True
print(isinstance(myset, (list ,tuple))) # False


# Example 3: Check for custom classes using inheritance
class Animal:
    pass


class Dog(Animal):
    pass


class Cat(Animal):
    pass


class Bird:
    pass

dog = Dog()
cat = Cat()
bird = Bird()


print(isinstance(dog ,Animal)) # True
print(isinstance(cat ,Animal)) # True
print(isinstance(bird ,Animal)) # False

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions