• python笔记-面向对象-单例模式-特殊方法


    一、单例模式

    由于类的每一次实例都是不同的对象,在开发中可能需要每一次实例都必须是同一个对象,比如读取配置文件。这种模模式成为单例模式
    实现流程

    class Cls:
        i = None
    
        def __new__(cls, *args, **kwargs):
            if cls.i == 0:
                cls.i = super(Cls, cls).__new__(cls)
            return cls.i
    
    
    cl1 = Cls()
    cl2 = Cls()
    print(id(cl1), id(cl2))  # 1698079553136 1698079553136 同一个对象
    
    • __new__方法: 创建并返回一个实例的引用

    补充
    super(ClassName, self/cls): 调用上一级类的方法

    ClassName: 按继承顺序, 被调用方法类的下一级类名.
    self/cls: 当前使用这个方法的实例或这时类

    
    class A:
    
        def search(self):
            print("A类")
    
    
    class B:
        def search(self):
            print("B类")
    
    
    class C(A):
        def search(self):
            print("C类继承A类")
    
    
    class D(B):
        def search(self):
            print("D类继承B类")
    
    
    class E(C, D):
        def search(self):
            super(C, self).search()  # 调用A类的方法
    
    
    print(E.mro())
    
    e = E()
    e.search()
    

    二、特殊方法

    一个类可以通过定义具有特殊名称的方法来实现由特殊语法所引发的特定操作
    以下内容参考: https://www.cnblogs.com/nmb-musen/p/10861536.html 网页

    2.1 基本方法

    1. __new__(cls[, ...]): 调用以创建一个 cls 类的新实例, 并返回实例的引用给 self(新建实例时触发)
    2. __init__(self[, ...]): 构造器,当一个实例被创建的时候调用的初始化方法(实例化时触发)
    3. __del__(self): 析构器,当一个实例被销毁的时候调用的方法(销毁实例时触发)
    4. __call__(self[, args...]): 允许一个类的实例像函数一样被调用(类被当成函数调用时触发)
    5. __repr__(self): 当被 repr() 调用时的行为; 此方法通常被用于调试,因此确保其表示的内容包含丰富信息且无歧义是很重要的。
    6. __str__(self): 通过 str(object) 以及内置函数 format()print() 调用以生成一个对象的“非正式”或格式良好的字符串表示
    7. __bytes__(self): 当被 bytes() 调用时的行为, 生成一个对象的字节串表示。这应该返回一个 bytes 对象
    8. __hash__(self): 当被 hash() 调用时的行为
    9. __bool__(self): 当被 bool() 调用时的行为,应该返回 True 或 False
    10. __format__(self, format_spec): 当被 format() 调用时的行为

    2.2 属性相关

    1. __getattr__(self, name): 当用户试图获取一个不存在的属性时的行为(访问属性失败后触发)
    2. __getattribute__(self, name): 当该类的属性被访问时的行为(getattr()obj.name 触发此方法)
    3. __setattr__(self, name, value): 当一个属性被设置时的行为(setattr()obj.name = value触发此方法)
    4. __delattr__(self, name): 当一个属性被删除时的行为(delattr()del obj.name触发此方法)
    5. __dir__(self): 当 dir() 被调用时的行为
    6. __get__(self, instance, owner): 当描述符的值被取得时的行为
    7. __set__(self, instance, value): 当描述符的值被改变时的行为
    8. __delete__(self, instance): 当描述符的值被删除时的行为

    2.3 比较运算符行为

    1. __lt__(self, other): 定义小于号的行为:x < y 调用 x.__lt__(y)
    2. __le__(self, other): 定义小于等于号的行为:x <= y 调用 x.__le__(y)
    3. __eq__(self, other): 定义等于号的行为:x == y 调用 x.__eq__(y)
    4. __ne__(self, other): 定义不等号的行为:x != y 调用 x.__ne__(y)
    5. __gt__(self, other): 定义大于号的行为:x > y 调用 x.__gt__(y)
    6. __ge__(self, other): 定义大于等于号的行为:x >= y 调用 x.__ge__(y)

    2.4 算术运算符行为

    1. __add__(self, other): 加法的行为:+
    2. __sub__(self, other): 减法的行为:-
    3. __mul__(self, other): 乘法的行为:*
    4. __truediv__(self, other): 真除法的行为:/
    5. __floordiv__(self, other): 整数除法的行为://
    6. __mod__(self, other): 取模算法的行为:%
    7. __divmod__(self, other): 当被 divmod() 调用时的行为
    8. __pow__(self, other[, modulo]): 当被 power() 调用或 ** 运算时的行为
    9. __lshift__(self, other): 按位左移位的行为:<<
    10. __rshift__(self, other): 按位右移位的行为:>>
    11. __and__(self, other): 按位与操作的行为:&
    12. __xor__(self, other): 定义按位异或操作的行为:^
    13. __or__(self, other): 定义按位或操作的行为:|

    2.5 反运算符行为

    1. __radd__(self, other): 与__add__相同,当左操作数不支持(+)时被调用
    2. __rsub__(self, other): 与__sub__相同, 当左操作数不支持(-)时被调用
    3. __rmul__(self, other): 与__mul__相同, 当左操作数不支持(*)时被调用
    4. __rtruediv__(self, other): 与__truediv__相同, 当左操作数不支持(/)时被调用
    5. __rfloordiv__(self, other): 与__floordiv__相同,当左操作数不支持(//)时被调用
    6. __rmod__(self, other): 与__mod__相同,当左操作数不支持(%)时被调用
    7. __rdivmod__(self, other): 与__divmod__相同,当左操作数不支持(divmod())时被调用
    8. __rpow__(self, other): 与__pow__相同,当左操作数不支持(**)时被调用
    9. __rlshift__(self, other): 与__lshift__相同,当左操作数不支持(<<)时被调用
    10. __rrshift__(self, other): 与__rshift__相同,当左操作数不支持(>>)时被调用
    11. __rand__(self, other): 与__and__相同,当左操作数不支持(&)时被调用
    12. __rxor__(self, other): 与__xor__相同,当左操作数不支持(^)时被调用
    13. __ror__(self, other): 与__or__相同,当左操作数不支持(|)时被调用

    2.6 增强赋值运算符行为

    1. __iadd__(self, other): 赋值加法的行为:+=
    2. __isub__(self, other): 赋值减法的行为:-=
    3. __imul__(self, other): 赋值乘法的行为:*=
    4. __itruediv__(self, other): 赋值真除法的行为:/
    5. __ifloordiv__(self, other): 赋值整数除法的行为://
    6. __imod__(self, other): 赋值取模算法的行为:%
    7. __ipow__(self, other[, modulo]): **= 运算时的行为
    8. __ilshift__(self, other): 赋值按位左移位的行为:<<=
    9. __irshift__(self, other): 赋值按位右移位的行为:>>=
    10. __iand__(self, other): 赋值按位与操作的行为:&=
    11. __ixor__(self, other): 赋值定义按位异或操作的行为:^=
    12. __ior__(self, other): 赋值定义按位或操作的行为:|=

    2.7 一元运算符行为

    1. __pos__(self): 正号的行为:+x
    2. __neg__(self): 负号的行为:-x
    3. __abs__(self): 当被 abs() 调用时的行为
    4. __invert__(self): 按位求反的行为:~x

    2.8 类型转换行为

    1. __complex__(self): 当被 complex() 调用时的行为(需要返回恰当的值)
    2. __int__(self): 当被 int() 调用时的行为(需要返回恰当的值)
    3. __float__(self): 当被 float() 调用时的行为(需要返回恰当的值)
    4. __round__(self[, n]): 当被 round() 调用时的行为(需要返回恰当的值)
    5. __index__(self):
      • 当对象是被应用在切片表达式中时,实现整形强制转换
      • 如果你定义了一个可能在切片时用到的定制的数值型,你应该定义 index
      • 如果 index 被定义,则 int 也需要被定义,且返回相同的值
    6. __enter__(self):
      • 定义当使用 with 语句时的初始化行为
      • __enter__ 的返回值被 with 语句的目标或者 as 后的名字绑定
    7. __exit__(self, exc_type, exc_value, traceback):
      • 定义当一个代码块被执行或者终止后上下文管理器应该做什么
      • 一般被用来处理异常,清除工作或者做一些代码块执行完毕之后的日常工作

    2.9 容器类型行为

    1. __len__(self): 当被 len() 调用时的行为(返回容器中元素的个数)
    2. __getitem__(self, key): 获取容器中指定元素的行为,相当于 self[key]
    3. __setitem__(self, key, value): 设置容器中指定元素的行为,相当于 self[key] = value
    4. __delitem__(self, key): 删除容器中指定元素的行为,相当于 del self[key]
    5. __iter__(self): 当迭代容器中的元素的行为
    6. __reversed__(self): 当被 reversed() 调用时的行为
    7. __contains__(self, item): 当使用成员测试运算符(in 或 not in)时的行为
  • 相关阅读:
    循环神经网络(Recurrent Neural Network)
    特征选择
    程序猿能挣多少钱
    python socket
    python 2 encode and decode
    pandas series
    source collection list
    pep8摘要
    python 正则表达式
    django显示图片
  • 原文地址:https://www.cnblogs.com/duyupeng/p/13161002.html
Copyright © 2020-2023  润新知