Methods and Functions

Python dir()

The function dir python is responsible for returning the valid list of the attributes for the objects in the current local scope. 

For example:

If an object of a method called is named as __dir__(), the function must return a list of attributes that are associated with that function. 

dir python

Source Code

dir() Parameters

The dir python function has a maximum of one optional parameter.

  1. Object-returns the list of the attributes of this object. 

Return Value from dir()

The dir python function is responsible for returning all the valid list of attributes of the object.

If the object has a _dir_() method, the method will be called, and it must return all the list of attributes it contains. 

Some examples to explain the functionality of the fir() are given below:

Example 1:

To acquire a list of valid attributes, use the following example. It only accepts one parameter, which is optional.

Source Code

                    

att = dir()  

# Displaying result  

print(att)  

Output:

['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__',

 '__spec__']

Example 2:

This function returns attributes linked to an object if we pass it a parameter. Here’s an example.

Source Code

                    

lang = ("C","C++","Java","Python")  

# Calling function  

att = dir(lang)  

# Displaying result  

print(att)  

Output:

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',

'__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', 

'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', 

'__subclasshook__', 'count', 'index']

Example 3:

Source Code:

# Python dir() function example  

                    

class Student():  

def __init__(self,x):  

 return self.x  

# Calling function  

att = dir(Student)  

# Displaying the result  

print(att)  

Output:

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__',

Example 4:

The function dir() will be invoked if it is already defined in the object.

Source Code

                    

class Student():  

 def __dir__(self):  

        return [10,20,30]  

# Calling the function  

s = Student()  

att = dir(s)  

# Displaying result  

print(att)  



Output:

[10, 20, 30]

What is DIR in Python?

DIR in python is an inbuilt function that returns a list of any object’s attributes and methods (say functions, modules, strings, lists, dictionaries, etc.)

Look at the examples given below to understand how they function works:

Example 1: How dir() works?

                    

number = [1, 2, 3]

print(dir(number))



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__', 'number']

Example 2: dir() on User-defined Object

                    

class Person:

  def __dir__(self):

    return ['age', 'name', 'salary']

  

teacher = Person()

print(dir(teacher))

Output

['age', 'name', 'salary']

Example 3: Program to demonstrate the dir()

                    

import random

 
print("The random library's contents are as follows::")

 
print(dir(random))



Output : 

 
The random library's contents are as follows::


['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST',

'SystemRandom', 'TWOPI', '_BuiltinMethodType', '_MethodType', '_Sequence',

'_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',

'__name__', '__package__', '__spec__', '_acos', '_ceil', '_cos', '_e', '_exp',

'_inst', '_log', '_pi', '_random', '_sha512', '_sin', '_sqrt', '_test', '_test_generator',

'_urandom', '_warn', 'betavariate', 'choice', 'expovariate', 'gammavariate', 'gauss',

'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint',

'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform',

'vonmisesvariate', 'weibullvariate']

Is dir a keyword in Python?

The dir is not a keyword but is a built-in function in Python used to return all the attributes of the object. 

What is dir () in R?

The dir() in R is used to return all the character vectors that contain the names of the files and the folders in a directory. 

Syntax:

dir(path)

What is the function of Dir?

The dir() function returns all of the object’s properties and methods, but not their values. All properties and methods, including built-in properties that are the default for all objects, will be returned by the function. 

Without arguments, the method returns a list of names in the current local scope. Return a list of valid attributes for the object using an argument.

Source Code:

                    

class Person:

  name = "John"

  age = 36

  country = "Norway"



print(dir(Person))



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', 'country', 'name']

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

Your email address will not be published. Required fields are marked *

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.