Thursday 23 September 2021

Python: dir(): return all the attributes, methods of an object

Signature

dir([object])

 

dir() is a built-in function, it returns list of the attributes and methods of an object.

 

Let’s see it with an example.

 

dir_demo.py

primes = [2, 3, 5, 7]

print(dir(primes))

 

Output

['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

 

The default dir() mechanism behaves differently with different types of objects.

 

a.   If the object is a module object, the list contains the names of the module’s attributes.

b.   If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.

c.    Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment