Python isinstance() Function
- Contact No: 4587963245
- Email ID: [email protected]
- Website: https://docs.vultr.com/python/built-in/isinstance
- Street: india
- City: jukil
- State: Please select
- Zip/Postal Code: 112625
- Country: India
- Listed: November 19, 2024 2:47 pm
- Expires: 27 days, 9 hours
Description
In Python, the isinstance() function is used to check if an object is an instance or subclass of a particular class or data type. This built-in function is very useful when you want to confirm that an object is of the expected type before performing operations on it.
Syntax:
python
Copy code
isinstance(object, classinfo)
object: The object you want to check.
classinfo: This can be a class, a tuple of classes, or a data type. If the object is an instance of any class in the tuple, isinstance() will return True.
The isinstance() function returns a boolean value:
True if the object is an instance of the class or a subclass of it.
False otherwise.
Example 1: Basic Usage
Let’s start with a basic example to check if a variable is an instance of a specific class.
python
Copy code
x = 10
print(isinstance(x, int)) # Output: True
y = “Hello”
print(isinstance(y, str)) # Output: True
In this example:
x is an integer, so isinstance(x, int) returns True.
y is a string, so isinstance(y, str) returns True.
Example 2: Checking Multiple Types
isinstance() can also check if an object is an instance of one of several classes by using a tuple.
python
Copy code
z = 5.7
print(isinstance(z, (int, float))) # Output: True
Here, z is a floating-point number, so isinstance(z, (int, float)) returns True, as z is an instance of float, which is part of the tuple.
Example 3: Checking Class Inheritance
Another useful feature is checking if an object is an instance of a subclass of a particular class.
python
Copy code
class Animal:
pass
class Dog(Animal):
pass
a = Animal()
d = Dog()
print(isinstance(d, Animal)) # Output: True
print(isinstance(a, Dog)) # Output: False
In this case, Dog is a subclass of Animal, so isinstance(d, Animal) returns True because d is an instance of Dog, which inherits from Animal.
Example 4: Combining isinstance() with Custom Classes
isinstance() can also be applied to custom classes, ensuring that objects are instances of the desired class or its subclasses.
python
Copy code
class Shape:
pass
class Circle(Shape):
pass
circle = Circle()
print(isinstance(circle, Shape)) # Output: True
Here, circle is an instance of the Circle class, which is a subclass of Shape, so isinstance(circle, Shape) returns True.
Conclusion
The isinstance() function is a powerful tool in Python for type checking. It helps ensure that objects are of the expected type, which is crucial for debugging and writing reliable code. Whether you’re working with built-in types, custom classes, or checking class inheritance, isinstance() makes it easier to handle types dynamically.
6 total views, 1 today