Fundamentals 5 min read

Understanding Python Magic (Special) Methods with Practical Examples

This article explains Python's magic (special) methods such as __init__, __str__, __getitem__, __setitem__, __len__, __eq__, __iter__, __next__, __enter__, __exit__, __call__, and __del__, providing clear descriptions and runnable code examples for each in Python programming.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Understanding Python Magic (Special) Methods with Practical Examples

Python's magic methods (also called special methods) are identified by double underscores at the beginning and end of a method name. They allow developers to define custom behavior for class instances in operations such as object creation, initialization, comparison, iteration, attribute access, and more.

1. __init__ method : Initializes object attributes.

class MyClass:
  def __init__(self, name):
    self.name = name

obj = MyClass("John")
print(obj.name)  # 输出 "John"

2. __str__ method : Returns a string representation of the object.

class MyClass:
  def __init__(self, name):
    self.name = name

  def __str__(self):
    return f"MyClass(name={self.name})"

obj = MyClass("John")
print(obj)  # 输出 "MyClass(name=John)"

3. __getitem__ method : Enables indexing to access elements.

class MyList:
  def __init__(self):
    self.data = [1, 2, 3, 4, 5]

  def __getitem__(self, index):
    return self.data[index]

my_list = MyList()
print(my_list[2])  # 输出 3

4. __setitem__ method : Allows assigning values to indexed positions.

class MyList:
  def __init__(self):
    self.data = [1, 2, 3, 4, 5]

  def __setitem__(self, index, value):
    self.data[index] = value

my_list = MyList()
my_list[2] = 10
print(my_list[2])  # 输出 10

5. __len__ method : Returns the length of the object.

class MyList:
  def __init__(self):
    self.data = [1, 2, 3, 4, 5]

  def __len__(self):
    return len(self.data)

my_list = MyList()
print(len(my_list))  # 输出 5

6. __eq__ method : Defines equality comparison between objects.

class Point:
  def __init__(self, x, y):
    self.x = x
    self.y = y

  def __eq__(self, other):
    return self.x == other.x and self.y == other.y

point1 = Point(1, 2)
point2 = Point(1, 2)
print(point1 == point2)  # 输出 True

7. __iter__ and __next__ methods : Make an object iterable.

class MyRange:
  def __init__(self, start, end):
    self.start = start
    self.end = end

  def __iter__(self):
    return self

  def __next__(self):
    if self.start >= self.end:
      raise StopIteration
    value = self.start
    self.start += 1
    return value

my_range = MyRange(1, 5)
for num in my_range:
    print(num)  # 输出 1, 2, 3, 4

8. __enter__ and __exit__ methods : Define a context manager.

class MyContext:
  def __enter__(self):
    print("Entering the context")
    return self

  def __exit__(self, exc_type, exc_value, traceback):
    print("Exiting the context")

with MyContext() as context:
    # 执行上下文中的操作
    print("Inside the context")

9. __call__ method : Makes an object callable like a function.

class MyCallable:
  def __call__(self, *args, **kwargs):
    print("Calling the object")

my_callable = MyCallable()
my_callable()  # 输出 "Calling the object"

10. __del__ method : Defines behavior when an object is destroyed.

class MyClass:
  def __del__(self):
    print("Deleting the object")

obj = MyClass()
del obj  # 输出 "Deleting the object"

These examples demonstrate how magic methods can be used to customize class and object behavior, providing greater flexibility and functionality in Python programming.

pythonOOPexamplesSpecial MethodsMagic Methods
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.