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)
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:
__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
person = Person("Alice", 30, "Software Engineer")
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']
__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"]
custom_person = CustomPerson("Bob", 35, "Data Scientist")
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.
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)
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)
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)
Customizing attribute listing with dir
:
class CustomDirObject: def __dir__(self): return ["custom_attr", "another_attr"] obj = CustomDirObject() attributes = dir(obj) print(attributes)
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)
Exploring object properties with dir
:
class PropertyObject: @property def computed_property(self): return "Computed Value" obj = PropertyObject() attributes = dir(obj) print(attributes)
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)
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)
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)
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)
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}")
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)