Python is one of the most popular programming languages in the world, used by developers in various industries. It is an object-oriented programming language, which means that everything is an object in Python.
One of the essential features of Python is the ability to check the type of an object. In Python, you can check the type of an object using the isinstance()
function.
1) Using the isinstance()
function in Python:
The isinstance()
function is a built-in function in Python used to check if an object is of a specific type. The function takes two arguments: the object and the class or data type.
It returns
True
if the object belongs to the specified class or data type or any of its subclasses; otherwise, it returns False
. Syntax of isinstance()
function:
The syntax of the isinstance()
function is straightforward.
Here’s how it looks like:
isinstance(object, classinfo)
The first argument specifies the object whose type needs to be checked, while the second argument classinfo
is the class or data type in which the object is checked for. Example of using isinstance()
function:
Consider the following example:
a = 10
print(isinstance(a, int))
The output of the above code will be
True
because the variable “a” is an integer. Here, we check whether the variable “a” belongs to the “int” class or not.
2) isinstance()
function with built-in types:
Python provides many built-in types such as int
, float
, string
, list
, tuple
, dict
, set
, and None
, among others. You can use the isinstance()
function to check the type of these built-in types.
Checking different built-in types using isinstance()
:
Consider the following example:
a = 10
b = 1.0
c = "Hello"
d = [1,2,3]
e = (1,2,3)
f = {"name": "John", "age": 30}
g = {1,2,3}
print(isinstance(a,int))
print(isinstance(b,float))
print(isinstance(c,str))
print(isinstance(d,list))
print(isinstance(e,tuple))
print(isinstance(f,dict))
print(isinstance(g,set))
The output of the above code will be:
True
True
True
True
True
True
True
Here, we have checked the type of different built-in types using the isinstance()
function. Checking isinstance()
with None
:
None
is a special constant in Python that represents the absence of a value.
You can use the isinstance()
function to check if a variable has no value. Consider the following example:
a = None
print(isinstance(a, type(None)))
The output of the above code will be
True
since variable ‘a’ has no value. Conclusion:
The isinstance()
function in Python is essential for checking the type of an object.
It helps in ensuring that the code is working with the expected data types, which can prevent runtime errors. The function works with built-in data types such as integers, floats, strings, lists, tuples, sets, and dictionaries, among others.
By knowing how to use isinstance()
, you can improve the quality and reliability of your Python code. 3) isinstance()
with multiple classes:
In Python, you can check if an object belongs to multiple classes using the isinstance()
function with a tuple of multiple classes.
This is useful when you want to check if an object belongs to more than one class. Checking isinstance()
with multiple types using a tuple:
Consider the following example:
a = 10
b = 1.0
print(isinstance(a, (int, float)))
print(isinstance(b, (int, float)))
The output of the above code will be:
True
True
Here, we have checked if the variables “a” and “b” belong to either the “int” or the “float” class. Example of checking isinstance()
with multiple types:
Consider the following example:
my_list = [1,2,3]
def check_type(obj):
if isinstance(obj, (int,list)):
print("Object is either an integer or a list.")
else:
print("Object is neither an integer nor a list.")
check_type(my_list)
The output of the above code will be:
Object is either an integer or a list.
Here, we created a function that takes an object as an argument and checks if the object is either an integer or a list. 4) isinstance()
with Python classes:
In Python, you can create your own classes and use the isinstance()
function to check if an object belongs to your class.
Checking isinstance()
with Python classes:
Consider the following example:
class Employee:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
return self.age == other.age and self.name == other.name
employee1 = Employee("John", 30)
print(isinstance(employee1, Employee))
The output of the above code will be:
True
Here, we created a class called Employee
with its name and age attributes. We then instantiated an object of the Employee
class called employee1
and checked if it belongs to the Employee
class using the isinstance()
function.
Example of checking isinstance()
with Python class:
Consider the following example:
class Employee:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
return self.age == other.age and self.name == other.name
employee1 = Employee("John", 30)
employee2 = Employee("Mike", 25)
if isinstance(employee1, Employee) and isinstance(employee2, Employee) and employee1 == employee2:
print("Employees are the same.")
else:
print("Employees are different.")
The output of the above code will be:
Employees are different.
Here, we instantiated two objects of the Employee
class called employee1
and employee2
.
We then used the isinstance()
function to check if both employees belong to the Employee
class and compared them using the comparison operator. As they have different names and ages, the output is “Employees are different.”
Conclusion:
In Python, isinstance()
is an essential function used to check if an object belongs to a specific class or data type.
You can check if an object belongs to multiple classes using a tuple. Additionally, you can create your own classes and use the isinstance()
function to check if an object belongs to your class.
By knowing how to use isinstance()
, you can develop more reliable and error-free Python code. 5) isinstance()
function with inheritance:
In Python, you can use inheritance to define a new class from an existing one.
The new class defined is called a subclass, while the existing class is called a superclass. You can use the isinstance()
function to check if an object is an instance of the superclass or subclass.
Checking isinstance()
function with inheritance:
Consider the following example:
class Developer:
def __init__(self, name, age):
self.name = name
self.age = age
class PythonDeveloper(Developer):
pass
dev = PythonDeveloper("John", 30)
print(isinstance(dev, Developer))
print(isinstance(dev, PythonDeveloper))
The output of the above code will be:
True
True
Here, we have defined two classes, Developer
and PythonDeveloper
. PythonDeveloper
is a subclass of Developer
.
We then created an object of the PythonDeveloper
class called “dev” and checked if it belongs to the Developer
and PythonDeveloper
classes. Example of using isinstance()
function with inheritance:
Consider the following example:
class Developer:
def __init__(self, name, age):
self.name = name
self.age = age
class PythonDeveloper(Developer):
pass
class CppDeveloper(Developer):
pass
python_dev = PythonDeveloper("John", 30)
cpp_dev = CppDeveloper("Mike", 25)
for dev in [python_dev, cpp_dev]:
if(isinstance(dev, Developer)):
print(dev.name, "is a developer.")
else:
print(dev.name, "is not a developer.")
The output of the above code will be:
John is a developer.
Mike is a developer.
Here, we defined three classes, Developer
, PythonDeveloper
, and CppDeveloper
.
PythonDeveloper
and CppDeveloper
are subclasses of Developer
. We then created objects of the PythonDeveloper
and CppDeveloper
classes and looped through them to check if they are instances of the Developer
class.
6) isinstance()
with Python list:
A list is a built-in data type in Python that can store multiple values. You can use the isinstance()
function to check if an object is a list or if an element inside the list is a nested list.
Additionally, you can use isinstance()
to check if all elements of a list are of the same type. Checking if an object is an instance of a list type:
Consider the following example:
my_list = [1,2,3]
print(isinstance(my_list, list))
The output of the above code will be:
True
Here, we created a list called “my_list” and checked if it belongs to the list data type using the isinstance()
function. Checking if an element of a list is a nested list:
Consider the following example:
my_list = [1,2,[3,4],5]
for elm in my_list:
if(isinstance(elm, list)):
print(elm, " is a list.")
else:
print(elm, "is not a list.")
The output of the above code will be:
1 is not a list.
2 is not a list.
[3, 4] is a list.
5 is not a list.
Here, we looped through the list “my_list” and checked if each element is a list using the isinstance()
function.
Checking if elements of a list are numbers or strings:
Consider the following example:
my_list = [1,2,"Hello",3,"World"]
for elm in my_list:
if(isinstance(elm, (int,float))):
print(elm, "is a number.")
elif(isinstance(elm, str)):
print(elm, "is a string.")
else:
print(elm, "is neither a number nor a string.")
The output of the above code will be:
1 is a number.
2 is a number.
Hello is a string.
3 is a number.
World is a string.
Here, we looped through the list “my_list” and checked if each element is a number or a string using the isinstance()
function with multiple classes.
Checking if all elements of a list are of the same type:
Consider the following example:
my_list1 = [1,2,3]
my_list2 = [1,2,"3"]
my_list3 = ["Hello","World"]
if(all(isinstance(elm, int) for elm in my_list1)):
print("All elements of my_list1 are of the same type.")
else:
print("Not all elements of my_list1 are of the same type.")
if(all(isinstance(elm, int) for elm in my_list2)):
print("All elements of my_list2 are of the same type.")
else:
print("Not all elements of my_list2 are of the same type.")
if(all(isinstance(elm, str) for elm in my_list3)):
print("All elements of my_list3 are of the same type.")
else:
print("Not all elements of my_list3 are of the same type.")
The output of the above code will be:
All elements of my_list1 are of the same type.
Not all elements of my_list2 are of the same type.
All elements of my_list3 are of the same type.
Here, we checked if all elements of the list are of the same type using the isinstance()
function along with the all
function.
Conclusion:
Inheritance is an essential feature of Object-Oriented Programming, and isinstance()
helps in checking if an object is an instance of a superclass or subclass. You can use isinstance()
to check if an object is a list, a nested list, or if all elements of a list are of the same type.
By knowing how to use isinstance()
, you can improve your Python code’s quality by ensuring that the right data types are used throughout the program. In conclusion, isinstance()
is a significant Python function that plays a crucial role in ensuring that objects or variables are of the right data type.
It helps prevent runtime errors and unexpected results. You can use isinstance()
to check built-in types, user-defined classes, inheritance, and Python lists.
By understanding how to use the function, you can write reliable and robust code. It is essential to ensure the correct data type to avoid errors, making use of isinstance()
is essential while writing Python code.