Python built-in Method - dir()
The dir() method is a built-in function in Python that returns a list of valid attributes and methods of an object. If no argument is passed to dir(), it returns a list of names in the current local scope.
Here is the syntax for dir() method:
dir([object])
where object is an optional parameter that specifies the object whose attributes and methods need to be listed. If object is not specified, dir() returns a list of names in the current local scope.
Here is an example of how to use dir():
class MyClass:
def __init__(self):
self.x = 10
self.y = 20
def my_method(self):
pass
obj = MyClass()
# list the attributes and methods of 'obj'
print(dir(obj))
In this example, we define a MyClass class with x and y attributes and my_method() method. We then create an object obj of the MyClass class. We use dir() to list the attributes and methods of obj. The output of the dir() function includes the __init__() method, my_method() method, x attribute, and y attribute.
dir() is often used in conjunction with the built-in hasattr() method to check if an object has a specific attribute or method. Here is an example:
class MyClass:
def __init__(self):
self.x = 10
self.y = 20
def my_method(self):
pass
obj = MyClass()
if hasattr(obj, 'x'):
print('obj has attribute x')
if hasattr(obj, 'my_method'):
print('obj has method my_method')
In this example, we check if obj has the x attribute and my_method() method using hasattr(). If an object has a specified attribute or method, hasattr() returns True. We then use print() to print a message indicating whether the object has the specified attribute or method.
