How to know or check if an object has an attribute in Python? There are several different methods you can use to check if an object has an attribute or not. For example, using the built-in hasattr()
function, getattr()
method and more.
In this article, we’ll explore the different methods for checking if an object has an attribute in Python, and provide code examples to help you understand how to use each method effectively.
1. Quick Examples of Checking Object has an Attribute
The following examples demonstrate several different methods for checking if an object has an attribute. These examples will give you a good high-level overview, we will discuss each method in more detail later on.
# Method 1: Using hasattr()
if hasattr(my_object, 'my_attribute'):
print('my_object has the "my_attribute"')
else:
print('my_object does not have "my_attribute"')
# Method 2: Using try/except with getattr()
try:
value = getattr(my_object, 'my_attribute')
print('my_object has "my_attribute"')
except AttributeError:
print('my_object does not have "my_attribute"')
# Method 3: Using dir() and in
if 'my_attribute' in dir(my_object):
print('my_object has "my_attribute"')
else:
print('my_object does not have "my_attribute"')
# Method 4: Using the vars() function
if 'my_attribute' in vars(my_object):
print('my_object has "my_attribute"')
else:
print('my_object does not have "my_attribute"')
2. hasattr() – Check Object has an Attribute
The hasattr()
is a built-in Python function that allows you to check if an object has a specific attribute. The function returns True
if the object has the attribute, and False
otherwise.
The syntax for hasattr()
is as follows:
# Syntax of hasattr()
hasattr(object, attribute)
Where object
is the object you want to check for the presence of an attribute, and attribute
is a string representing the name of the attribute you want to check for.
First, let’s create a class with some attributes.
# Create a custom class
class Car:
make = "Ford"
model = "Mustang"
def __init__(self, year):
self.year = year
def start(self):
print("Engine started.")
Now let’s create an object for the class and check if that object contains an attribute.
# Create an object
object= Car(2023)
# CHeck object has an attribute
print(hasattr(object, "year"))
# True
print(hasattr(object, "color"))
# False
print(hasattr(object, "make"))
# True
Remember we will be using this class throughout the tutorial.
3. getattr() – Get Attribute of an Object if it Exists
The getattr()
function returns the value of a named attribute of an object. This function takes two arguments: the object to retrieve the attribute from, and the name of the attribute to retrieve.
The Syntax of the getattr()
function is :
# Syntax of getattr()
getattr(object, name[, default])
The description of the parameters is :
object
: The object to retrieve the attribute from.name
: A string representing the name of the attribute to retrieve.default
: An optional value to return if the attribute is not found. If this argument is not provided and the attribute is not found, aAttributeError
is raised.
Example of using the getattr()
function to know if an object has an attribute or not:
print(getattr(object, "year"))
# 2023
print(getattr(object, "color"))
# Error
print(getattr(object, "make"))
# "Ford"
It will raise AttributeError
if the attribute doesn’t exist. So use it with exception handling.
4. dir() – List All Attributes of an Object
The dir()
function returns a list of the attributes and methods of an object. When called without an argument, it returns the names in the current scope. The returned list is not sorted and may contain duplicates due to multiple inheritances.
Syntax of the dir()
function is :
# Syntax of dir()
dir([object])
object
(optional): The object to inspect. If no object is provided, dir()
returns the names in the current local scope.
print(dir(object))
# Output:
# ['__class__', '__delattr__', ....., 'make', 'model', 'start', 'year']
5. vars() – Know Attributes with its Value
The vars()
function returns the __dict__
attribute of an object. The __dict__
attribute is a dictionary that contains the object’s instance attributes and their values.
# Using vars()
object= Car(2023)
print(vars(object))
# Output:
# {'year': 2023}
One unique thing about vars()
is that it can be used to retrieve the instance attributes and their values of an object in a dictionary format. This is different from dir()
, which only returns the list of attribute names and doesn’t include their values.
6. dict attribute – Know if an Object Has Attribute
In Python, every object has a __dict__
attribute which is a dictionary containing the object’s attributes and their values. We can use this attribute to check if an object has a certain attribute.
object= Car(2023)
if 'year' in object.__dict__:
print("has a 'year'")
else:
print("does not have a 'year'")
if 'color' in object.__dict__:
print("has a 'color'")
else:
print("does not have a 'color'")
# output:
# has a 'year'
# does not have a 'color'
7. Summary and Conclusion
We have covered different ways to know or check if an object has an attribute in Python by using the hasattr()
, getattr()
, dir()
, and vars()
functions, as well as the __dict__
attribute, can all be effective methods for checking if an object has a particular attribute. If you have any questions please leave a comment below.
Happy coding!
Related Articles
- Python Class attribute Properties
- Static or Class Variables in Python?
- Python Objects Explained
- Null Object in Python
- Print Object Properties and Values in Python?
- Convert JSON Object to String in Python
- Explain Classes & Objects in Python
- Check object has an attribute in Python
- Check Given Object is a List or not in Python
- Python Check if Key Exists in Dictionary
- Python Check if File Exists