Python dir

Share

                   Python dir


In Python, the dir() function is a built-in function that returns a list of all the names (attributes and methods) in the current local scope or the given object. It can be used to inspect the contents of a module, class, or any other object that supports attributes.

Here’s the basic syntax of the dir() function:

python
dir([object])
  • If object is not provided, dir() returns the names in the current local scope.
  • If object is provided, dir(object) returns the names in the scope of the given object.

Let’s see some examples:

  1. Using dir() without an object to inspect the current local scope:
python
def example_function():
x = 42
y = "Hello"
return x + y

print(dir())

Output:

css
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'example_function']

In this example, dir() returns a list of names in the current scope, which includes the function example_function and some built-in names like '__name__', '__doc__', etc.

  1. Using dir() with an object to inspect its attributes and methods:
python
class MyClass:
def __init__(self):
self.x = 10

def my_method(self):
return "Hello from my_method"

my_object = MyClass()
print(dir(my_object))

Output:

css
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'my_method', 'x']

Here, dir(my_object) returns a list of attribute and method names associated with the my_object instance of the MyClass class.

dir() can be very useful for exploring the contents of Python objects, especially in interactive environments like the Python shell or Jupyter notebooks.

Python Training Demo Day 1

You can find more information about Python in this Python Link

 

Conclusion:

Unogeeks is the No.1 IT Training Institute for Python  Training. Anyone Disagree? Please drop in a comment

You can check out our other latest blogs on Python here – Python Blogs

You can check out our Best In Class Python Training Details here – Python Training

💬 Follow & Connect with us:

———————————-

For Training inquiries:

Call/Whatsapp: +91 73960 33555

Mail us at: info@unogeeks.com

Our Website ➜ https://unogeeks.com

Follow us:

Instagram: https://www.instagram.com/unogeeks

Facebook: https://www.facebook.com/UnogeeksSoftwareTrainingInstitute

Twitter: https://twitter.com/unogeeks


Share

Leave a Reply

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