In the course of learning and using Python, you must have come across special methods that start and end with two underscores, also known as Magic methods or Dunder methods. Such as:

>>> dir(int)
['__abs__'.'__add__'.'__and__'.'__bool__'.'__ceil__'.'__len__'.'__delattr__'.'__dir__'.'__divmod__'.'__doc__'.'__eq__'.'__float__'. ]Copy the code

* Python's built-in data types implement a number of magical methods, which can be viewed through dir().

Learning magic for the first time

When we want to get the first element from an array nums = [1, 2, 3], we know we just need to execute nums[0]. To get the value of nums[0], the Python compiler actually implicitly calls nums.__getitem__(0).

>>> nums = [1.2.3]
>>> nums[0]
1
>>> nums.__getitem__(0)
1
Copy the code

To get the length of an array, len(nums) is used. The Python compiler calls the special nums.__len__() method.

>>> len(nums)
3
>>> nums.__len__()
3
Copy the code
  • Special methods exist for implicit calls by the Python compiler
  • We don’t need to call it when we write our own programs
  • By specification, you cannot define methods like _ _xx_

The effect of magic methods

Operator overloading

In Python, + can add to two ints and concatenate strings, all of which are magic tricks that keep the language consistent.

Magic methods are used extensively for operator overloading, such as +, -, *, and /. We can define our own data structures or data types, and these custom classes can be identical to Python’s built-in data types, making it possible to write more expressive code, in other words, more Pythonic code.

Hands-on practice

Let’s create a class called tool man that supports addition, multiplication, greater than or equal to, and so on

class ToolMan(object) :

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

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

    def __str__(self) :
        return "Hello, worker!"

    def __add__(self, other) :
        Add up the ages of the two toolmen
        return self.age + other.age

    def __mul__(self, other) :
        Multiply the ages of the two toolmen
        return self.age * other.age

    def __ge__(self, other) :
        # Compare the age of the ToolMan
        return self.age >= other.age

Copy the code

We custom such a class, you can find that the class overrides a lot of magic methods, these magic methods can let you custom class also implement interger addition, subtraction, multiplication, division, size and other operations!

>>> tool_man1 = ToolMan("Working Man 1".20)
>>> tool_man2 = ToolMan("Working Man 2".25)
>>> print(Tool_man1) Hello, worker!>>> tool_man1 + tool_man2
45
>>> tool_man1 * tool_man2
500
>>> tool_man1 >= tool_man2
False
Copy the code

Is not also very interesting, oneself begin to play a play ~

List of special methods

reference

  • Docs.python.org/3/reference…