Built-in Functions to Check Conditions in Python
Python provides several built-in functions that can be used to check conditions, types, or attributes of objects. These functions help in validating data and controlling the flow of programs.
1. isinstance()
- Definition: Checks if an object is an instance or subclass of a class or a tuple of classes.
- Usage: Used for type checking.
Example:
num = 10
print(isinstance(num, int)) # Output: True
text = "Hello"
print(isinstance(text, str)) # Output: True
Output
True
True
True
2. issubclass()
- Definition: Checks if a class is a subclass of another class or a tuple of classes.
- Usage: Used for class hierarchy validation.
Example:
class Animal:
pass
class Dog(Animal):
pass
print(issubclass(Dog, Animal)) # Output: True
print(issubclass(Dog, object)) # Output: True
Output
True
True
True
3. hasattr()
- Definition: Checks if an object has a specified attribute.
- Usage: Used to avoid attribute errors.
Example:
class Car:
def __init__(self):
self.make = "Toyota"
car = Car()
print(hasattr(car, 'make')) # Output: True
print(hasattr(car, 'model')) # Output: False
Output
True
False
False
4. callable()
- Definition: Checks if an object appears callable (e.g., functions or methods).
- Usage: Used to verify if you can call an object.
Example:
def greet():
return "Hello"
print(callable(greet)) # Output: True
print(callable(5)) # Output: False
Output
True
False
False
5. len()
- Definition: Returns the number of items in an object (e.g., lists, strings, dictionaries).
- Usage: Used to determine the size of collections.
Example:
my_list = [1, 2, 3, 4, 5]
print(len(my_list)) # Output: 5
my_string = "Hello"
print(len(my_string)) # Output: 5
Output
5
5
5
Conclusion
These built-in functions are essential for performing checks and validations in Python. They help ensure that the data types and structures used in the code behave as expected, promoting robustness and reliability in programming.