Python 的 Magic Method

In Python, all methods enclosed by "__" double underscores are collectively called "magic methods". For example, __init__ , which we have the most contact with. What do magic methods do?

Using these magic methods, we can construct beautiful code and encapsulate complex logic into simple methods.

So what are the magic methods in a class?

We can use Python's built-in method dir() to list all the magic methods in the class. The example is as follows:

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
class User(object):
    pass
if __name__ == '__main__':
    print(dir(User()))

Output results:

badddbb0006fcb132dcd3477ce09ea1.png

As you can see, there are quite a lot of magic methods in a class, and the screenshots are not complete, but we only need to understand some common and commonly used magic methods.

Continuing Learning
||
submitReset Code