常用的python内置魔法函数的介绍与使用
1.什么是魔法函数?
在python中,有的名称会在前面和后面都加上两个下划线,例如__init__,__str__,__call__,__repr__,__new__等等像这样的函数就被称为魔法函数,每次在代码中看到这些函数都头痛,决定写一篇博客好好弄清楚这些函数的作用与用法。
先创建一个类来包含一些常用的魔法函数
class magic_mtehod(object):
def __new__(cls):
pass
def __init__(self):
pass
def __str__(self):
pass
def __repr__(self):
pass
def __iter__(self):
pass
def __call__(self):
pass
def __len__(self):
pass
2.魔法函数的具体使用
__new__与__init__
构造方法包括创建对象和初始化对象,在python当中,分为两步执行:先执行 __new__方法,然后执行__init__方法;
__init__是当实例对象创建完成后被调用的,然后设置对象属性的一些初始值。
__new__是在实例创建之前被调用的,因为它的任务就是创建实例然后返回该实例,是个静态方法。
也就是, __new__在__init__之前被调用, __new__的返回值(实例)将传递给__init__方法的第一个参数,然后__init__给这个实例设置一些参数。
class magic_mtehod(str):
def __new__(cls, string):
temp = super().__new__(cls, string)
print(id(temp))
return temp
def __init__(self,string):
print(id(self))
test = magic_mtehod("Hello World!")
print(id(test))
输出:
139742323368368
139742323368368
139742323368368
上面这段代码的内容很简单&#x