
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if an Object Has an Attribute in Python
Python is an object-oriented programming language, here attributes are known as properties of an object. By using different methods, we can check if an object has an attribute or not.
To check if an object contains a particular attribute then we can use hasattr() method and getattr() method. Or if we want to get all existing attributes then we can use the dir() method. (Learn more about Python directories: Python Directories Tutorial)
Initially create a dummy Python class with two attributes then assign it to an object, and it will refer throughout this article.
class DummyClass(): var1 = 'Value1' var2 = 2 obj = DummyClass()
Accessing attributes directly
In this example we try to access the attribute of an object directly, here we might get an AttributeError if the attribute doesn't exist. If we don't get an AttributeError, then will know the object has the attribute.
Example
For the above example the object does not contain the attribute "a", and it contains "var1", "var2" attributes.
class DummyClass(): var1 = 'Value1' var2 = 2 obj = DummyClass() print(obj.var1) print(obj.var2) print(obj.a)
Output
Value1 2 Traceback (most recent call last): File "/home/cg/root/57371/main.py", line 8, inprint(obj.a) AttributeError: 'DummyClass' object has no attribute 'a'
Accessing attributes using the getattr() method
Same as direct attributes accessing like the above example the getattr() method also returns the value of the named attribute (if it exists), and returns AttributeError if the attribute doesn't exist.
Syntax
getattr(object, name[, default])
This function has three parameters, the name of the object whose attributes have to be found, name which attribute we want to check, and finally [, default] it accepts a default argument which will be printed if the attribute does not exist instead of generating the AttributeError.
Example
The getattr() method returns the values of the existing attributes and throws the default arguments or AttributeError for the nonexistent attributes.
print(getattr(obj, 'var1', 'Attribute doesn't exist')) print(getattr(obj, 'var2', 'Attribute doesn't exist')) print(getattr(obj, 'a', 'Attribute doesn't exist')) print(getattr(obj, 'a'))
Output
Value1 2 Attribute doesn't exist Traceback (most recent call last): File "/home/cg/root/17209/main.py", line 9, inprint(getattr(obj, 'a')) AttributeError: 'DummyClass' object has no attribute 'a'
Accessing attributes using the hasattr() method
The hasattr() method checks if an object has a specific attribute or not. The hasattr() method is implemented by using the getattr() method.
Syntax
hasattr(object, name )
This function has two parameters, the name of the object and attribute name, which we want to check. And returns a Boolean (True/False). It returns 'True' if the attribute is present in that object otherwise it will return 'False'.
Example
The obj method does not contains the "a" attribute so that it returns False. And for var1, var2 attributes it returns True as output.
class DummyClass(): var1 = 'Value1' var2 = 2 obj = DummyClass() print(hasattr(obj, 'var1')) print(hasattr(obj, 'var2')) print(hasattr(obj, 'a'))
Output
True True False
Accessing all existing attributes by using the dir() method
The dir() method returns a list which contains all attributes of the object, also it will return the keys included in the __dict__ attribute.
Syntax
dir(object)
For some objects the dir() results may not be accurate, because the functionality might be modified using __getattr__ method.
Example
The dir() method returns the list of all existing attributes.
class DummyClass(): var1 = 'Value1' var2 = 2 obj = DummyClass() print(dir(obj))
Output
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'var1', 'var2']