Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
No results
  • About AskPython
  • Blog
  • Contact Me
  • Free Online Developer Tools Hub
  • Home
  • Meet the Team
  • Privacy Policy
  • Python
  • Python Course for Beginners Online FREE
  • Python Tutorial – Mega Index
  • Terms and Conditions

🚀 Supercharge your YouTube channel's growth with AI.

Try YTGrowAI Free
  • Home
  • Blog
  • About AskPython
  • Python Course
  • Start Here

Quick Overview of the Python dir() Method

  • SnehSneh
  • May 4, 2020
  • Built-in Methods
Quick Overview of the Python dir() Method

Today we are going to discuss the Python dir() method.

So let’s get started.

The Python dir() Method Basics

The dir() method in Python is widely used to get the list of names of the attributes of the passed object in an alphabetically sorted manner.

dir([object])

Here, object is an optional argument. When any Python object is passed to the dir() method, it returns a list containing all the attributes of that object. And when nothing is passed, the method returns back the list of all the local attributes.

For objects with defined __dir__() method, the dict() leads to the call for it and hence should return a list of attributes related to the object.

Python dir() Example

Now that we have a basic idea of the dir() method, let us take a look at an example to have a better understanding.

#empty dir()
print("dir() :", dir())

#list initialisation
list1 = ['name', 'class', 'roll']

#dictionary initialisation
dict1 = {0: 'bad', 5: 'fair', 10: 'good'}

print("\ndir(list1) :", dir(list1))
print("\ndir(dict1) :", dir(dict1))

Output:

dir() : ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']

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

dir(dict1) : ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

As you can see, here we have at first passed nothing, then a list object, and finally a dictionary object to the dir() method and have printed out the returned list.

From the above output, we can clearly see the different attributes available for the list and dictionary objects. For the case where nothing is passed to the function, we get all the names of the methods or attributes in the local scope.

Working with the dir() Method in Python

So now let us try out some more examples where we try to use the dir() function on objects of user-defined classes as well as ones with defined __dir__() method.

1. With Custom Objects

Now that we have applied the dir() method for built-in classes like lists and dictionaries. Let us try finding out the results for custom objects of a user-defined class with undefined __dir__().

#class
class shape:
    name = "rectangle"
    sides = 4

obj = shape()
print(dir(obj)) #dir for our custom object

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

Here, obj is an object of the shape class with name rectangle and sides = 4. Passing this obj object to the dir() method, we get the above set of attributes.

Note, this list includes the name as well as the sides variable too.

2. With defined __dir__()

As mentioned earlier in this article, for objects with defined __dir__() method, the dir() method calls the corresponding __dir__() method which must again return a list of attributes.

Let us try to understand that with an example.

#class
class shape:
    name = "rectangle"
    sides = 4
    def __dir__(self):
        return ['Square','Circle']

obj = shape()
print(dir(obj)) #dir for our custom object

Output:

Python dir method output
Python dir() method output

As you can see, for the object obj of the shape class, the __dir__() method is called and the above list of attributes is returned at the site of dir(obj) call.

Conclusion

So in this tutorial, we learned about the Python dir() method, how it works as well as how we can use it in different cases.

For any further questions related to this topic, feel free to comment below.

References

  • Python dir() function – Journal Dev Article,
  • Why is ‘dir()’ named ‘dir’ in python? – StackOverflow Question,
  • Python dir() – Official Documentation.
Sneh
Sneh
Articles: 36
How the Python issubclass() Method works?
Previous Post How the Python issubclass() Method works?
Next Post Convert string to datetime using Python strptime()
Convert string to datetime using Python strptime()

Related Posts

Print Function Python: Arguments and Output

Print Function Python: Arguments and Output

  • November 28, 2026
How to Use Input Function in Python

How to Use Input Function in Python

  • November 28, 2026
How to Open Files in Python

How to Open Files in Python

  • November 23, 2026

Partner Websites

  • GoLangDocs
  • LinuxForDevices
  • CodeForGeek

Popular Categories

  • Python Programming
  • Python Modules
  • OOPS in Python
  • Python Programming Examples
  • Strings in Python

Hall of Fame

  • Python Programming
  • OOPS in Python
  • Creating Python Modules
  • Args and Kwargs in Python
  • Python Dictionary (Dict) Tutorial
  • Python List – 15 Things You MUST Know
  • Python Set – Things You MUST Know
  • Python String Functions: Methods by Task

Important Links

  • Home
  • Python Course
  • Start Here
  • Blog
  • About AskPython
Latest posts
  • np.linalg.eig: Eigenvalues and Eigenvectors
  • What Does %s Mean in a Python Format String?
  • How to Use np.sin() in NumPy
  • cv2.imread: Load Images with OpenCV
  • pd.read_json: Read JSON Into a DataFrame

Copyright © 2026 - AskPython. All rights reserved.