Python高级(3)魔法方法

2018-12-13  本文已影响0人  錦魚

常用魔法方法整理

def __init__(self)

初始化

  • 创建实例时调用
def __str__(self):

实例字符串方法

  • 打印类时调用
def __repr__(self):

类字符串方法

  • 类调用
def call(self):

方法调用

  • 以方法的形式调用
def __del__(self)

删除方法

  • 删除实例时调用
def __new__(self)

单例

  • 对象实例化的时候调用
    单例例子

    class Dog():
        __instance = None
        def __new__(cls):
            if cls.__instance = None:
                cls.__instance = object.__new__(cls)
            return cls.__instance
    
  • 详细1

  • 详细2

  • 执行顺序


def bases(self):

获取指定类的所有父类构成元素

  • 使用方法为类名 . __bases__
def __mro__(self):

显示指定类的所有继承脉络和继承顺序

  • 使用方法为类名 . __mro__

def __all__(self)

__all__魔法方法只针对通过 from xx import *这种导入方式有效

  • __all__ = ['函数名或方法名']的方式限制一下哪些函数或方法可以被导
    all方法详解
上一篇 下一篇

猜你喜欢

热点阅读