写给编程高手的Python教程目录
什么是魔法函数
魔法函数是一个网络名词,大致就是以双下划线开头,双下划线结尾的函数就是魔法函数。例如下列代码:
class Company:
def __init__(self, employee_list):
self.employee = employee_list
def __str__(self):
return ",".join(self.employee)
def __repr__(self):
return ",".join(self.employee)
def __len__(self):
return len(self.employee)
def __getitem__(self, item): # __开头 __结尾的函数
return self.employee[item]
# def __iter__(self):
# pass #优先使用迭代器,然后尝试getitem
魔法函数主要是给python解释器“阅读”、“执行”调用的函数。
company = Company(["tom", "bob", "jane"])
len(company) # 调用__len__函数
for em in company: # 调用__getitem__函数,1、2、3、4...直到抛出异常
print(em)
扩展:notebook 安装:pip install notebook 启动:ipython notebook
魔法函数一览
- 非数学运算:
class Nums:
def __init__(self, num):
self.num = num
def __abs__(self):
return abs(self.num)
my_num = Nums(-10)
print(abs(my_num))
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, v):
return Vector(self.x + v.x, self.y + v.y)
def __str__(self):
return "({x},{y})".format(x=self.x, y=self.y)
first = Vector(1, 2)
second = Vector(3, 4)
print(first + second)
鸭子类型
动态语言都拥有鸭子类型这种特质,而魔法函数正是Python解释器提供的一组协议接口。