In this tutorial, we’ll break down some common fundamental concepts in Python: classes, attributes, objects, and the powerful built-in functions isinstance()
and hasattr()
. These topics are the building blocks of object-oriented programming (OOP) in Python and will help you write more efficient, organized code.
Scope
This blog is a beginner-friendly guide to understanding Python’s isinstance()
, hasattr()
, and basic OOP concepts like classes, objects, and attributes. It includes simple explanations and practical examples.
Purpose
The goal is to help beginner developers and system administrators:
- Understand classes, objects, and attributes in Python.
- Learn how to use
isinstance()
to check an object’s type. - Use
hasattr()
to verify if an object has specific attributes.
By the end, developer will have a basic understanding of these concepts and be able to apply them in Python.
What is a Class?
A class is like a blueprint for creating objects. It defines the structure and behavior of the objects you want to create. In simpler terms, a class defines what properties (called attributes) and methods (functions inside a class) an object will have.
Example of a Class:
# Define a class called Car class Car: def __init__(self, brand, model): self.brand = brand # Attribute self.model = model # Attribute def start_engine(self): print(f"The {self.brand} {self.model}'s engine has started.")
In this example:
Car
is the class.brand
andmodel
are attributes of theCar
class.start_engine
is a method that prints a message about starting the car’s engine.
What is an Object?
An object is an instance of a class. Think of an object as a specific example of the blueprint (class). When you create an object from a class, you can assign it different values for the attributes defined by the class.
Example of an Object:
# Create an object (instance) of the Car class my_car = Car(brand="Honda", model="Brio") # Call the method start_engine on the object my_car.start_engine()
Here, my_car
is an object (or instance) of the Car
class. We created it with the brand “Honda” and the model “Brio”. We can now use this object to call its methods and access its attributes.
What are Attributes?
Attributes are variables inside a class that store data related to the object. Each object can have different values for its attributes.
In the example above:
brand
andmodel
are attributes of theCar
class.my_car.brand
will return"Honda"
andmy_car.model
will return"Brio"
.
isinstance() – Checking the Type of an Object
The isinstance()
function checks if a given object belongs to a specific class (or any of its parent classes). This is helpful to ensure you’re working with the right kind of object before performing operations on it.
Syntax:
isinstance(object, classinfo)
- object: The object you want to check.
- classinfo: The class (or tuple of classes) you want to compare the object against.
Example of isinstance():
# Create another object my_truck = Car(brand="Ford", model="Territory") # Check if my_truck is an instance of the Car class if isinstance(my_truck, Car): print(f"{my_truck.brand} {my_truck.model} is a type of Car.") else: print("This is not a Car.")
In this example, isinstance(my_truck, Car)
checks if my_truck
is an instance of the Car
class. If it is, we print a message confirming it’s a car.
hasattr() – Checking if an Object has an Attribute
The hasattr()
function is used to check if an object has a specific attribute. This is useful when you’re not sure if an object has certain attributes or if you’re working with dynamically created objects.
Syntax:
hasattr(object, attribute)
- object: The object you want to check.
- attribute: The name of the attribute (as a string) you’re checking for.
Example of hasattr():
# Check if my_car object has a 'brand' attribute if hasattr(my_car, 'brand'): print(f"My car's brand is {my_car.brand}.") else: print("This object does not have a 'brand' attribute.")
In this example, hasattr(my_car, 'brand')
checks if the object my_car
has a brand
attribute. If it does, we access and print the value.
Bringing it All Together: Example
Let’s use both isinstance()
and hasattr()
in a simple scenario where we create a list of various objects and check their types and attributes.
# Define another class class Bicycle: def __init__(self, brand, type_of_bike): self.brand = brand self.type_of_bike = type_of_bike # Create objects my_bike = Bicycle(brand="Giant", type_of_bike="Mountain Bike") my_truck = Car(brand="Ford", model="Territory") # List of objects vehicles = [my_car, my_bike, my_truck] # Loop through the objects for vehicle in vehicles: if isinstance(vehicle, Car): print(f"This is a car: {vehicle.brand} {vehicle.model}") elif isinstance(vehicle, Bicycle): print(f"This is a bicycle: {vehicle.brand} {vehicle.type_of_bike}") # Check if the object has a 'brand' attribute if hasattr(vehicle, 'brand'): print(f"Brand: {vehicle.brand}") else: print("No 'brand' attribute.")
Output:
This is a car: Honda Brio Brand: Honda This is a bicycle: Giant Mountain Bike Brand: Giant This is a car: Ford Territory Brand: Ford
Summary
- Classes are blueprints for creating objects.
- Objects are instances of classes.
- Attributes store data related to an object.
isinstance()
checks if an object belongs to a specific class.hasattr()
checks if an object has a specific attribute.
By understanding these basic concepts, you can write more robust and flexible code in Python. Knowing how to use isinstance()
and hasattr()
will allow you to interact with objects more safely and dynamically.