Explanation and Examples of Python Special Methods (__unicode__, __delattr__, __del__, __dict__, __all__)
This article explains the purpose and usage of several Python special methods—including __unicode__, __delattr__, __del__, __dict__, and __all__—and provides concrete code examples illustrating how each method works in practice.
In Python, several special methods allow developers to customize object behavior, such as __unicode__, __delattr__, __del__, __dict__, and __all__.
__unicode__() is used in Python 2 to define an object's Unicode string representation, invoked by the unicode() function or print statements.
__delattr__() is called when the del statement removes an attribute, enabling custom deletion logic.
__del__() is executed when an object is garbage‑collected, allowing cleanup of resources.
__dict__() provides a dictionary of an object's attributes, accessible via obj.__dict__ or vars(obj).
__all__ defines the public symbols of a module; when using from module import *, only names listed in __all__ are imported.
Example code demonstrates each method:
class MyClass:
def __init__(self, value):
self.value = value
def __unicode__(self):
return u"MyClass with value: %s" % self.value
obj = MyClass(42)
print(unicode(obj)) # Output: MyClass with value: 42
class MyClass:
def __init__(self, value):
self.value = value
def __delattr__(self, name):
if name == 'value':
raise AttributeError("Cannot delete attribute 'value'")
obj = MyClass(42)
del obj.value # Raises AttributeError: Cannot delete attribute 'value'
class MyClass:
def __del__(self):
print("MyClass object is being destroyed")
obj = MyClass()
del obj # Output: MyClass object is being destroyed
class MyClass:
def __init__(self, value):
self.value = value
obj = MyClass(42)
print(obj.__dict__) # Output: {'value': 42}
# my_module.py
__all__ = ['my_function']
def my_function():
return "Hello, world!"
def internal_function():
return "This function is not part of __all__"
# In another file
from my_module import *
print(my_function()) # Output: Hello, world!
print(internal_function()) # Raises NameErrorNote that __unicode__() is only relevant for Python 2; in Python 3 the __str__() method should be used, and __all__ applies to modules rather than regular classes.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.