Python dir() Built in Function

The dir() function in Python is used to get a list of attributes and methods of an object. The dir() function takes an object as an argument and returns a list of strings containing the names of its attributes and methods. The object can be any Python data type or user-defined class. Here are some examples of using dir() in Python:

Get all the attributes and methods of a built-in Python object:

 >>> dir(list)
['__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']

Get all the variables and functions defined in a module:

import math
print(dir(math))

Output:

['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

Get all the attributes and methods of a user-defined class:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age


    def say_hello(self):
        print("Hello, my name is", self.name)


p = Person("Alice", 30)
print(dir(p))

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__', 'age', 'name', 'say_hello']

As you can see, dir() is a very useful function for exploring the attributes and methods of different Python objects.

Some more examples:

# Use dir() with a string
s = "Hello"
result = dir(s)
print(result) # Output: ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', ...]


# Use dir() with a list
l = [1, 2, 3]
result = dir(l)
print(result) # Output: ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', ...]


# Use dir() with a user-defined class
class Student():
    def __init__(self, name):
        self.name = name


    def greet(self):
        print(f"Hello, {self.name}!")


stu = Student("Alice")
result = dir(stu)
print(result)
# Output: ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', ... 'greet', 'name']

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions