面向对象之魔术方法

在Python中,所有以“__”双下划线包起来的方法,都统称为“Magic Method”(魔术方法),例如类的初始化方法 __init__ ,Python中所有的魔术方法均在官方文档中有相应描述,这边给大家把所有的魔术方法汇总了一下,希望对大家的学习有所帮助。

1、__new__方法

__new__ 是在一个对象实例化的时候所调用的第一个方法

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

    def __new__(cls, *args, **kwargs):
        print("这是new方法")
        # return super().__new__(cls)  #调用父类的new方法进行对象实例化
        return object.__new__(cls)

m=MyClass('test')
print(m.name)

运行结果:

这是new方法
test

使用__new__方法实现单例模式

class MyClass(object):
    _instance=None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance=object.__new__(cls)
        return cls._instance

m1=MyClass()
m1.name="test"
m2=MyClass()
m2.name='test1'
m3=MyClass()
m3.age=18
print(id(m1))  #4463655848
print(id(m2))  #4463655848
print(id(m3))  #4463655848
print(m1.name)  #test1
print(m3.age)   #18

 2、__str__和__repr__方法

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

   def __str__(self):
       print("调用__str__方法")
       return self.name  #返回值必须为字符串

   def __repr__(self):
       print("调用__repr__方法")
       return "My_object:{}".format(self.name)  #返回值必须为字符串
   
m=MyClass("musen")
print(m.name)
print("------------")
print(str(m))
print("------------")
print(repr(m))

运行结果:

musen
------------
调用__str__方法
musen
------------
调用__repr__方法
My_object:musen

总结:

使用str函数或print打印对象时,会优先调用自身的str方法,没有str方法时,会调用repr方法,如果两个方法都没有,会去找父类的str方法

使用repr方法或交互环境下输出变量,会找自身的repr方法,如果自身没有repr方法,会找父类的repr方法

注意点:

重写__str__和__repr__方法时,必须记得写return,return返回的必须是一个字符串对象。

 3、__call__方法

想让类创建出来的对象,像函数一样被调用,可以在类里面定义__call__方法。

class MyClass():
    def __init__(self,name):
        self.name=name

    def __call__(self):
        print("调用了call方法")

m=MyClass("test")
m()   # 运行结果:调用了call方法

通过__call__方法用类实现装饰器

#类实现装饰器
class Deractor():
    def __init__(self,func):
        self.func=func

    def __call__(self,*args,**kwargs):
        print("这是装饰器里面的第一个功能")
        result=self.func()
        print("这是装饰器里面的第二个功能")
        return  result


@Deractor
def test_01():  #test_01=Deractor(test_01)
    print("—————原来的功能函数——————————")
    return 'haha'

res=test_01()
print(res)

运行结果:

这是装饰器里面的第一个功能
—————原来的功能函数——————————
这是装饰器里面的第二个功能
haha

4、算术相关的方法

__add__(self,other):定义加法的行为 +

__sub__(self,other): 定义减法的行为 -

class MyStr():
    def __init__(self,data):
        self.data=data

    def __str__(self):
        return self.data

    def __add__(self,other):
        return  self.data+other.data

    def __sub__(self,other):
        return self.data.replace(other.data,'')

s1=MyStr("ssss111")
s2=MyStr("ssss222")

print(s1)  # ssss111
print(s2)  # ssss222

s3=MyStr(s1+s2)
print(s3)  # ssss111ssss222
print(s3-s1)  # ssss222
原文地址:https://www.cnblogs.com/crystal1126/p/13552322.html