Python Tutorial

Python Variable

Python Operators

Python Sequence

Python String

Python Flow Control

Python Functions

Python Class and Object

Python Class Members (properties and methods)

Python Exception Handling

Python Modules

Python File Operations (I/O)

Python __dir__() method: List all attribute (method) names of an object

The __dir__() method in Python is a special method that, when implemented, returns a list of attribute names for an object. If the __dir__() method is not implemented for a class, Python provides a default implementation that returns the list of attributes of the object, including the attributes from its class and its base classes.

Here's a step-by-step tutorial on how to use the __dir__() method in Python:

  • Define a class without the __dir__() method: Create a class with an __init__() method to initialize some instance attributes.
class Person:
    def __init__(self, name, age, occupation):
        self.name = name
        self.age = age
        self.occupation = occupation
  • Create an instance of the class: Instantiate the class to create an object with specific attribute values.
person = Person("Alice", 30, "Software Engineer")
  • Use the built-in dir() function: When you call the built-in dir() function on an object without a custom __dir__() method, Python uses the default implementation.
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', 'name', 'occupation']
  • Define a class with the __dir__() method: Create a class with an __init__() method, some instance attributes, and a custom __dir__() method.
class CustomPerson:
    def __init__(self, name, age, occupation):
        self.name = name
        self.age = age
        self.occupation = occupation

    def __dir__(self):
        return ["name", "age", "occupation", "custom_attribute"]
  • Create an instance of the CustomPerson class: Instantiate the CustomPerson class to create an object with specific attribute values.
custom_person = CustomPerson("Bob", 35, "Data Scientist")
  • Call the dir() function on the CustomPerson instance: When you call the dir() function on an object with a custom __dir__() method, Python uses the custom implementation.
print(dir(custom_person))

Output:

['age', 'custom_attribute', 'name', 'occupation']

In this tutorial, you learned how to use the __dir__() method in Python to customize the output of the built-in dir() function for a class. By implementing a custom __dir__() method, you can control the list of attributes displayed when the dir() function is called on an instance of your class. This can be useful for providing a cleaner interface or for hiding certain attributes from the user.

  1. How to use dir in Python to list object attributes:

    class SampleObject:
        def __init__(self, x, y):
            self.x = x
            self.y = y
    
    obj = SampleObject(42, "Hello")
    attributes = dir(obj)
    print(attributes)
    
  2. Inspecting object attributes with dir:

    class InspectableObject:
        def __init__(self, a, b):
            self.a = a
            self.b = b
    
    obj = InspectableObject(10, "World")
    attributes = dir(obj)
    print(attributes)
    
  3. Listing methods of an object using dir in Python:

    class MethodObject:
        def method1(self):
            pass
    
        def method2(self):
            pass
    
    obj = MethodObject()
    methods = [method for method in dir(obj) if callable(getattr(obj, method))]
    print(methods)
    
  4. Customizing attribute listing with dir:

    class CustomDirObject:
        def __dir__(self):
            return ["custom_attr", "another_attr"]
    
    obj = CustomDirObject()
    attributes = dir(obj)
    print(attributes)
    
  5. Dynamic attribute management with dir in Python:

    class DynamicDirObject:
        def __dir__(self):
            return [f"attr_{i}" for i in range(5)]
    
    obj = DynamicDirObject()
    attributes = dir(obj)
    print(attributes)
    
  6. Exploring object properties with dir:

    class PropertyObject:
        @property
        def computed_property(self):
            return "Computed Value"
    
    obj = PropertyObject()
    attributes = dir(obj)
    print(attributes)
    
  7. Object introspection using Python dir method:

    class IntrospectableObject:
        def __init__(self, x, y):
            self.x = x
            self.y = y
    
    obj = IntrospectableObject(42, "Hello")
    attributes = dir(obj)
    print(attributes)
    
  8. Filtering attributes with dir in Python:

    class FilteredAttributesObject:
        def __init__(self, a, b):
            self.a = a
            self.b = b
    
    obj = FilteredAttributesObject(10, "World")
    attributes = [attr for attr in dir(obj) if not attr.startswith("_")]
    print(attributes)
    
  9. Using dir for debugging in Python:

    class DebuggableObject:
        def __init__(self, x, y):
            self.x = x
            self.y = y
    
    obj = DebuggableObject(3, 7)
    attributes = dir(obj)
    print(attributes)
    
  10. Accessing hidden attributes with dir:

    class HiddenAttributesObject:
        def __init__(self, x, y):
            self._x = x
            self._y = y
    
    obj = HiddenAttributesObject(5, 10)
    hidden_attributes = [attr for attr in dir(obj) if attr.startswith("_")]
    print(hidden_attributes)
    
  11. Interactive object exploration with dir:

    class InteractiveObject:
        def __init__(self, a, b):
            self.a = a
            self.b = b
    
    obj = InteractiveObject(20, "Python")
    print("Interactive exploration:")
    for attribute in dir(obj):
        value = getattr(obj, attribute)
        print(f"{attribute}: {value}")
    
  12. Advanced usage of dir in Python:

    class AdvancedDirObject:
        def __dir__(self):
            original_attributes = set(dir(self))
            custom_attributes = {"custom_attr1", "custom_attr2"}
            return list(original_attributes.union(custom_attributes))
    
    obj = AdvancedDirObject()
    attributes = dir(obj)
    print(attributes)