多一句没有,少一句不行,用最短的时间,教会你有用的技术。

小伙伴们在群里聊到魔法函数,咱们刚好在学习这些基础知识,就来总结一下吧。

魔法函数的定义

先看看老外是怎么解释的:

Magic methods in Python are the special methods that start and end with the double underscores. They are also called dunder methods. Magic methods are not meant to be invoked directly by you, but the invocation happens internally from the class on a certain action.

意思就是说:以双下划线(__xx__)开始和结束的函数称之为为魔法函数,在类中它们会在恰当的时机被调用。自己不要随便去定义类似的函数,这样的话python可不认识哦。

下面来看一个例子:

  1. class Person(object):
  2. def __new__(cls, name, age):
  3. print("__new__我被创建了")
  4. return super(Person, cls).__new__(cls) #python3 的写法
  5. def __init__(self,name,age):
  6. print("__init__我被实例化了")
  7. self.name = name
  8. self.age = age
  9. def __str__(self):
  10. print("我被调用了!")
  11. return '<Person: %s(%s)>' % (self.name, self.age)
  12. if __name__ == '__main__':
  13. person =Person("小菜鸡",18)
  14. print(person)

魔法函数 - 图1

通过运行这段代码,我们可以看到,new方法的调用是发生在init之前的。其实当 你实例化一个类的时候,具体的执行逻辑是这样的:

  1. p = Person(name, age)
  2. 首先执行使用name和age参数来执行Person类的new方法,这个new方法会 返回Person类的一个实例(通常情况下是使用 super(Persion, cls).new(cls, … …) 这样的方式)。
  3. 然后利用这个实例来调用类的init方法,上一步里面new产生的实例也就是 init里面的的 self

面试也许会问: init 和 new 最主要的区别是什么?(仅作参考)

  1. init 通常用于初始化一个新实例,控制这个初始化的过程,比如添加一些属性, 做一些额外的操作,发生在类实例被创建完以后。它是实例级别的方法。

  2. new 通常用于控制生成一个新实例的过程。它是类级别的方法。

  3. new至少要有一个参数cls,代表要实例化的类,此参数在实例化时由Python解释器自动提供

  4. new必须要有返回值,返回实例化出来的实例,这点在自己实现new时要特别注意,可以return父类new出来的实例,或者直接是object的new出来的实例

  5. 可以将类比作制造商,new方法就是前期的原材料购买环节,init方法就是在有原材料的基础上,加工,初始化商品环节

看了好多中文解释还是不明白,来看下国外大佬咋说的:

The __new__() method returns a new object, which is then initialized by __init__().

  1. class Employee:
  2. def __new__(cls):
  3. print ("__new__ magic method is called")
  4. inst = object.__new__(cls)
  5. return inst
  6. def __init__(self):
  7. print ("__init__ magic method is called")
  8. self.name='Satya'
  1. emp = Employee()
  2. __new__ magic method is called
  3. __init__ magic method is called

魔法函数 - 图2

参考链接:

https://www.cnblogs.com/Sweepingmonk/p/11626971.html

常用的魔法函数

学过python的话,多多少少会认识一些。如果有不认识的,可以一个一个搜下学习下,加深对python的认识。

魔法函数 - 图3

魔法函数 - 图4

想了解更多的可以来这里看:

魔法函数 - 图5

魔法函数的详细解释可以看这个:

https://rszalski.github.io/magicmethods/

https://blog.csdn.net/L_zzwwen/article/details/93362318

魔法函数的作用

魔法函数可以为你写的类增加一些额外功能,方便使用者理解。比如,我们可以对魔法函数进行重写实现自己想要的效果。改天我们可以学习下单例模式,这应该算是对魔法函数的一种经典应用了。

本文主要是整理了下关于魔法函数的资料,用法都是官方定义好的,暂时没有特别需要解释的。

好了,今天的学习到此结束。