python进阶(四)~~~魔术方法

魔术方法

在python中,以双下划线开头、双下划线结尾的方法我们称之为魔术方法。例如__init__

魔术方法是python内部定义好的,我们不需要去创建。

1.__new__方法和单例模式

__new__方法:Create and return a new object.创建对象时触发
class Hero(object):

    def __init__(self,name):    # 对对象进行初始化
        print("这是init方法")
        self.name=name

    def __new__(cls,*args,**kwargs):    # 创建对象
        print("这是new方法")
        return super().__new__(cls)  # 必须返回原方法 创建对象的功能。如果缺少改行,h1返回值为None

h1=Hero("musen")
print(h1.name)

  应用:

  1. 重写new方法,返回其他的类对象;

  2.单例模式: 通常类每次实例化都会创建一个对象,通过单例模式可以实现限制 一个类只创建一个对象共用;

  单例模式实现思路:

  1.创建一个类属性记录是否创建过对象;

  2.在__new__方法中对类属性做出判断:如果没有创建,就新建一个对象并修改1种属性值;如果创建过,直接返回已创建的对象;

class Myclass(object):
    '''单例模式类'''
    instance=None

    def __new__(cls,*args,**kwargs):    # 创建对象
        if not cls.instance:
            cls.instance=object.__new__(cls)
            return cls.instance
        else:
             return cls.instance

h1=Myclass()
h2=Myclass()
h3=Myclass()
print(id(h1),id(h2),id(h3))

 2.上下文管理器

  通过with实现,底层使用两个魔术方法:object.__enter__()、object.__exit__()。一个类中只要使用了这两个方法,那么该类就实现了上下文协议,就是一个上下文管理器;

  object.__enter__(self): 输入此对象运行时使用的相关上下文;

  object.__exit__(self,exc_type,exc_val,exc_tb):  参数:异常类型、异常值、异常回溯

class Myopen(object):

    def __init__(self,filename,mode,encoding):
        self.filename=filename
        self.mode=mode
        self.encoding=encoding
        self.f=open(self.filename,self.mode,encoding=self.encoding)

    def __enter__(self):
        return self.f  # 返回打开的文件

    def __exit__(self,exc_type,exc_val,exc_tb):
        self.f.close()  # 关闭文件
     print(
exc_type,exc_val,exc_tb) #当执行出错时,打印出错误信息
with Myopen("1.txt","r",encoding="utf8") as f:
    print(f.read())

  上下文管理器的应用举例:

class Testcase(Myopen,unittest.TestCase):

    def __init__(self,*args,**kwargs):
        Myopen.__init__(self,*args,**kwargs)
        self,*args,**kwargs.__init__(self,*args,**kwargs)
        print("__init__")

t=Testcase()

3.__call__方法 : 在对象使用括号时被触发,使类创建的对象像函数一样可以被引用

class Test(object):

    def __call__(self):
        print("触发了call方法")

t=Test()
t()  # 触发了call方法

4.__str__方法、__repr__方法

  __str__方法:print()、str()、format() 触发

  __repr__方法:交互环境>>>下直接输入变量时、repr转换对象时 触发;当找不到__str__方法,只有__repr__方法时,上述3种均触发__repr__方法

  应用:打印类的一些属性

class Hero(object):
    def __init__(self,name):
        self.name=name

    def __str__(self):
        return self.name

h=Hero('musen')
print(h)

5. 算术运算的实现

  __add__(slef,other): 相加  +,以+触发

  __sub__(slef,other): 相减  -

  __mul__(slef,other): 相乘 *

  __truediv__(slef,other): 定义真除法 /

  __floordiv__(slef,other): 定义整数除法 //

  __mod__(slef,other): 定义取余算法 %

class Mystr(object):
    
    def __init__(self,value):
        self.value=value

    def __str__(self):
        return self.value
    
    def __add__(self,other):   # self代表实例本身,other代表其他
        return Mystr(F'{self.value}{other.value}')
  def __sub__(self,other):
return self.value.replace(other.value,'')
s1
=Mystr("aaa") s2=Mystr("bbb") print(s1+s2)
原文地址:https://www.cnblogs.com/qingyuu/p/12255570.html