In this tutorial we will explain how to acquire and print out all the available attributes for an Object in Python. There is more than one way of accomplishing this, so we will be discussing all of them in today’s tutorial.
Method#1 – Use dir()
The dir()
function is the most comprehensive and detailed function for getting all the attributes for an object. It not only returns a list of attributes for the object, but also accounts for any superclasses (parent classes).
class MyClass:
def __init__(self):
super().__init__()
self.name = "CodersLegacy"
self.id = 1
self.age = 20
obj = MyClass()
print(dir(obj))
['__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__', 'age', 'id', 'name']
The output contains many attributes, because these are the default attributes that all Python objects have. The new ones that we added are at the end of the list.
Method#2 – Use Docstrings
Another possible option is to rely on docstrings for an attribute list. Many big libraries such as Numpy add proper docstring within each Class/Function. These typically include a list of the attributes along with a short description as a bonus. Hence, this can be pretty helpful.
Here we will write some code to print out the docstring for a Numpy array.
import numpy as np
a = np.array([1, 2, 3])
print(a.__doc__)
The output is too large to fully include here, so we only included a small snippet.
...
Attributes
----------
T : ndarray
Transpose of the array.
data : buffer
The array's elements, in memory.
dtype : dtype object
Describes the format of the elements in the array.
imag : ndarray
Imaginary part of the array.
real : ndarray
Real part of the array.
size : int
Number of elements in the array.
itemsize : int
The memory use of each array element in bytes.
...
This will not always work, as some libraries do not have complete docstrings.
Method#3 – Use vars()
The third method we have is to use the vars()
function. As compared to dir()
, this function is not as extensive, and is more “local”. Examine the output below for a better understanding.
class MyClass:
def __init__(self):
super().__init__()
self.name = "CodersLegacy"
self.id = 1
self.age = 20
obj = MyClass()
print(vars(obj))
{'name': 'CodersLegacy', 'id': 1, 'age': 20}
As you can see here, only three attributes were printed. This is good if you only want to access the attributes local to this Class, and not the other default ones. As a bonus, you also get the current attribute values.
There is another technique that you may have heard of, which is to print out the __dict__
attribute of an object. This is actually the same as using vars()
, as the vars()
function itself uses the __dict__
attribute. For Python objects without a __dict__
attribute, the vars()
function will not work either.
This marks the end of the Print all attributes of an Object in Python Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.