GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Python/Article/python10/1.md at master · Msder/Python

Expand file tree

/

1.md

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
27 lines (16 loc) · 923 Bytes
/

1.md

Copy path

File metadata and controls

27 lines (16 loc) · 923 Bytes
Raw
Copy raw file
Download raw file
Edit and raw actions

一、Python 的 Magic Method

在 Python 中,所有以 "__" 双下划线包起来的方法,都统称为"魔术方法"。比如我们接触最多的 __init__ 。魔术方法有什么作用呢?

使用这些魔术方法,我们可以构造出优美的代码,将复杂的逻辑封装成简单的方法。

那么一个类中有哪些魔术方法呢?

我们可以使用 Python 内置的方法 dir() 来列出类中所有的魔术方法.示例如下:

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

class User(object):
    pass


if __name__ == '__main__':
    print(dir(User()))

输出的结果:

Python 类的魔术方法

可以看到,一个类的魔术方法还是挺多的,截图也没有截全,不过我们只需要了解一些常见和常用的魔术方法就好了。

You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.