In this tutorial, we will discuss about the dir() function in python programming language with the help of examples.
Python dir() function
The built-in python function is used to return a list of all valid attributes and methods of an object. The name of the object is passed to this method.
Syntax
dir([object])
Parameters of dir() function in python
The function in python takes only one optional argument or parameter i.e., object. Object whose list of all attributes is to be returned.
Return value of Python dir() function
• The python function is used to return a list of all valid attributes and methods of an object.
• If no parameters is passed to this method then the list of names in the current local space will be returned by this method.
Example 1: How Python dir() method works?
num = [14, 7, 2]print(dir(num))
print('\nReturn Value from empty dir()')
print(dir())
Output
['__add__', '__class__', '__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']Return Value from empty dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'num']
Example 2: Another example of python dir() function
class Result():def __init__(self,x):
return self.x
a = dir(Result)
print(a)
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__']
Example 3: Python dir() Function on User-defined Objectclass Student:
def __dir__(self)return ['Deepak', 'Reena', 'Ekta'
teacher = Student(
print(dir(teacher)))]:
Output
['Deepak', 'Ekta', 'Reena']