hasattr()
The built-in hasattr()
function allows you to check if an object has a specific attribute or method. It returns True
if the attribute is present and False
otherwise:
>>> class Dog:
... def bark(self):
... print("Woof")
...
>>> pluto = Dog()
>>> hasattr(pluto, "bark")
True
>>> hasattr(pluto, "meow")
False
hasattr()
Signature
hasattr(object, name)
Arguments
Argument | Description |
---|---|
object |
The object in which to look for the attribute or method. |
name |
A string representing the name of the attribute to check. |
Return Value
- Returns
True
if the object has the specified attribute or method andFalse
otherwise.
hasattr()
Examples
With built-in classes:
>>> hasattr(list, "append")
True
>>> hasattr(list, "put")
False
>>> hasattr(dict, "update")
True
>>> hasattr(dict, "next")
False
With an attribute name that exists in the object:
>>> class Car:
... def start(self):
... print("Car started")
...
>>> car = Car()
>>> hasattr(car, "start")
True
With an attribute name that doesn’t exist in the object:
>>> hasattr(car, "stop")
False
hasattr()
Common Use Cases
The most common use cases for the hasattr()
function include:
- Checking for the existence of an attribute or method before using it to avoid errors.
- Implement conditional logic based on available attributes or methods.
hasattr()
Real-World Example
Consider a scenario where you have different types of vehicles, and you want to perform operations based on the available features:
cars.py
class Car:
def start(self):
print("Car started")
class Bicycle:
def pedal(self):
print("Pedaling bicycle")
# Usage
vehicles = [Car(), Bicycle()]
for vehicle in vehicles:
if hasattr(vehicle, "start"):
vehicle.start()
elif hasattr(vehicle, "pedal"):
vehicle.pedal()
In this example, hasattr()
helps determine the available operation for each vehicle, allowing the code to execute the correct method without causing an error.
Related Resources
Tutorial
Duck Typing in Python: Writing Flexible and Decoupled Code
In this tutorial, you'll learn about duck typing in Python. It's a typing system based on objects' behaviors rather than on inheritance. By taking advantage of duck typing, you can create flexible and decoupled sets of Python classes that you can use together or individually.
For additional information on related topics, take a look at the following resources:
- Python's Built-in Functions: A Complete Exploration (Tutorial)
- Python Classes: The Power of Object-Oriented Programming (Tutorial)
- Object-Oriented Programming (OOP) in Python (Tutorial)
- Python's Built-in Functions: A Complete Exploration (Quiz)
- Class Concepts: Object-Oriented Programming in Python (Course)
- Inheritance and Internals: Object-Oriented Programming in Python (Course)
- Python Classes - The Power of Object-Oriented Programming (Quiz)
- Intro to Object-Oriented Programming (OOP) in Python (Course)
- Object-Oriented Programming (OOP) in Python (Quiz)