Python dir() method with example
Hello programmers, in this tutorial, we will learn the Python dir() method with examples.
dir({parameter}) method:
dir()
method is Python’s inbuilt method.- It takes only one parameter.
- It will return a list of functions and attributes of an object.
Example 1:
- It is an inbuilt method in Python, so we have no need to import anything
- 1st we simply call this function, and in 2nd example, we understand the behavior of this dir() method
#dir() method print(dir())
output:
['In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_dh', '_i', '_i1', '_ih', '_ii', '_iii', '_oh', 'exit', 'get_ipython', 'quit']
Example 2:
- To understand this dir() method, we have 1st create a list and a string and then we apply this method to it.
#list l l=[1,2,3,'a'] #string a="CodeSpeedy" #dir() method print(dir())
output:
['In', 'Out', '_', '_4', '_5', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_dh', '_i', '_i1', '_i2', '_i3', '_i4', '_i5', '_i6', '_i7', '_ih', '_ii', '_iii', '_oh', 'a', 'exit', 'get_ipython', 'l', 'quit']
Now you see in the 2nd output string variable ‘a’ and list variable ‘l’ was there in the output. So dir()
method basically returns the attribute present in the current cell.
Leave a Reply