9) d. dir Function Examples




Jane was fiddling around with an old locket in her attic. She suddenly teleported into a new dimension and wants to make sense of it.
Given the python class Dimension, write a program that finds all the attributes that are present in it and list them out.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Program:
#attributes.py

def list_attr(obj):
    print('\n'.join(dir(obj)))

#new_dimension.py
import attributes

class Dimension:
    def get_attributes(self):
        attributes.list_attr(self)

if __name__ =='__main__':
    dim = Dimension()
    dim.get_attributes()




Prof. Griffin is in his lecture and is teaching about python strings. In the midst of his lecture he wants a list of all the attributes that are present in a string class and wants you to answer the question. This is the last lecture of the day and you want to get it over with as soon as possible. Write a program that does the same so that you can enjoy the rest of your day.




Xen has been given a task by her professor to put an item in a list. He has the code ready but wants to know if there is an ‘append’ method in a python list or not. Write a method for him that checks if append is there in a list or not.

1
2
Output:
True




Tina has a large codebase and wants to know which modules have been imported in the program. Write a program for Tina so that she doesn’t have to read the whole codebase to find it out.

1
2
3
4
5
6
7
8
9
10
11
Program:
#check_imports.py

import math
import random
import sys
#...... some large code
import socket
import os

print(dir())
1
2
Output:
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'math', 'os', 'random', 'socket', 'sys']