什么是魔法函数?魔法函数它是一个网络术语,实际上是属于Python数据模型的概念。你只要记住魔法函数的作用就是增强你自定义类的功能。一般都会满足两个条件:
1.双下划线开头,双下划线结尾:比如__init__, __str__,__len__等 ;
2.定制类的特性, 看下面的例子你就知道了:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 遍历该公司的员工
class Company(object):
def __init__(self, employee_list):
self.employee = employee_list

company = Company(["tom", "bob", "jane"])
for employee in company.employee:
print(employee)


# 输出结果:
tom
bob
jane

现在我们来使用魔法函数,来增强我们这个Company类的功能(注意魔法函数不属于object,也不属于Company,只是用来增强某种功能而添加的)。这里我们使用魔法函数来让这个Company类具有可遍历的功能:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Company(object):
def __init__(self, employee_list):
self.employee = employee_list

def __getitem__(self, item):
return self.employee[item]

company = Company(["tom", "bob", "jane"])
for employee in company:
print(employee)

# 输出结果:
tom
bob
jane

看到没有,我们只是给它使用了一个__getitem__的魔法函数,这个类就可以直接被遍历了(Python解释器会去寻找这个__getitem__,存在就可以遍历)。其实迭代对象就是可以用for语句来进行遍历的,也就是说Python解释器首先会去寻找__iter__,如果没有就去寻找__getitem__,有就可以迭代,这就是刚才我们为什么可以进行遍历的原因。