Learning Sections show
dir, __dict__, and help Method in Python
Python provides several built-in functions and attributes that are useful for introspection and understanding objects and their attributes. Three such tools are dir()
, __dict__
, and help()
.
1. dir()
The dir()
function returns a list of the attributes and methods of an object. It can be used on any object to see its properties.
# Using dir() on a list
example_list = [1, 2, 3]
print(dir(example_list))
Output: ['__add__', '__class__', '__contains__', ... , 'append', 'clear', 'copy', ...]
2. __dict__
The __dict__
attribute is a dictionary representation of an object's attributes. It shows the object's attributes and their values.
# Define a simple class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Create an instance of the class
person = Person('John', 30)
print(person.__dict__)
Output: {'name': 'John', 'age': 30}
3. help()
The help()
function is used to display the documentation of modules, functions, classes, and methods. It provides a quick way to get information about Python objects.
# Using help() on a list
help(example_list)
Output: (Displays the documentation and available methods of the list object)