Magic Methods in Python Object-Oriented Programming (OOP)

🌟【❤️Welcome to follow and continue learning<span>Web Programming Notes</span>】🌟

Magic Methods in Python Object-Oriented Programming (OOP)

1.<span>__str__</span> and <span>__repr__</span> Differences

1. Detailed Explanation

In Python, <span>__str__</span> and <span>__repr__</span> are two magic methods used for string representation of objects, but they serve different purposes and are called in different contexts.

  • <span>__str__</span>:

    • Primarily used for a user-friendly string representation, typically displayed when printing an object.
    • Called when using the <span>print()</span> function or the <span>str()</span> function.
    • If <span>__str__</span> is not defined, Python will fall back to <span>__repr__</span>.
  • <span>__repr__</span>:

    • Primarily used for a developer-friendly string representation, typically for debugging and development.
    • Called when the object name is directly entered in the interactive interpreter.
    • If <span>__repr__</span> is not defined, Python provides a default implementation, usually <span><class_name object at memory_address></span>.
    • The goal of <span>__repr__</span> is to allow the string representation to recreate the object (i.e., <span>eval(repr(obj))</span> should return an equivalent object).

2. Code Example

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # Define __str__ method
    def __str__(self):
        return f"Person(name={self.name}, age={self.age})"

    # Define __repr__ method
    def __repr__(self):
        return f"Person('{self.name}', {self.age})"

# Create object
p = Person("A", 30)

# Use print() to print object, calls __str__
print(p)  # Output: Person(name=A, age=30)

# Directly input object name, calls __repr__
p  # Output: Person('A', 30)

3. Practical Application Scenarios

  • <span>__str__</span>:

    • Use <span>__str__</span> when you want users to see a concise, readable description of the object, such as when displaying object information in logging or user interfaces.
  • <span>__repr__</span>:

    • Use <span>__repr__</span> when you want to clearly see the internal state of the object during debugging and want the string representation to be usable for recreating the object, such as when viewing objects in a debugger.

2.<span>__getitem__</span> and <span>__setitem__</span> Examples

1. Detailed Explanation

  • <span>__getitem__</span>:

    • Used to implement indexing operations on objects, i.e., accessing elements in the object via <span>obj[key]</span>.
    • When using <span>obj[key]</span>, Python calls the <span>__getitem__</span> method and passes <span>key</span> as an argument.
  • <span>__setitem__</span>:

    • Used to implement indexing assignment operations on objects, i.e., setting elements in the object via <span>obj[key] = value</span>.
    • When using <span>obj[key] = value</span>, Python calls the <span>__setitem__</span> method and passes <span>key</span> and <span>value</span> as arguments.

2. Code Example

class MyDict:
    def __init__(self):
        self.data = {}

    # Define __getitem__ method
    def __getitem__(self, key):
        return self.data.get(key, None)  # Return None if key does not exist

    # Define __setitem__ method
    def __setitem__(self, key, value):
        self.data[key] = value

    # Define __repr__ method for easy viewing of object content
    def __repr__(self):
        return repr(self.data)

# Create object
my_dict = MyDict()

# Use __setitem__ to set values
my_dict['name'] = 'A'
my_dict['age'] = 30

# Use __getitem__ to get values
print(my_dict['name'])  # Output: A
print(my_dict['gender'])  # Output: None (because 'gender' does not exist)

# View object content
print(my_dict)  # Output: {'name': 'A', 'age': 30}

3. Practical Application Scenarios

  • <span>__getitem__</span> and <span>__setitem__</span>:
    • Use these two magic methods when you want your custom class to behave like built-in dictionaries or lists.
    • For example, implement a custom dictionary class, matrix class, or other data structures that require support for indexing operations.

4. In-Depth Principle Analysis

  • <span>__getitem__</span>:

    • When you use <span>obj[key]</span>, Python attempts to call <span>obj.__getitem__(key)</span>. If <span>__getitem__</span> is not defined, Python raises a <span>TypeError</span>.
  • <span>__setitem__</span>:

    • When you use <span>obj[key] = value</span>, Python attempts to call <span>obj.__setitem__(key, value)</span>. If <span>__setitem__</span> is not defined, Python raises a <span>TypeError</span>.

By implementing these two methods, you can enable your custom class to support indexing operations similar to built-in containers, thereby improving code readability and flexibility.

Through the above content, you should have a deep understanding of the magic methods <span>__str__</span>, <span>__repr__</span>, <span>__getitem__</span>, and <span>__setitem__</span> in Python, and be able to flexibly apply them in practical development.

Leave a Comment