
1 什么是魔法函数
class Company(object):
def __init__(self,employee_list):
self.employee=employee_list
#添加————getitem__方法以后变成了可迭代类型(魔法函数)
def __getitem__(self,item):
return self.employee[item]
company=Compant({'tom','bom','jane'])
#employee=company.employee
#for em in employee:
print(em)
company=company[:2]
#python语法和魔法函数结合的灵活性
for em in company1:
print(em)
#魔法函数:在python提供的以双下划线开头以双下划线结尾的函数叫魔法函数,可以随意的定制函数的特性,如果没有__iter__就会查找是否有__getitem__方法
2 python数据模型对python的影响
def__init__(self,employee__list):
self.employee =employee_list
# def __getitem__(self.item):
return self.employee[item]
def __len__(self):
return len(self.employee)
company =Company(['tom','bob','jane'])
company1=company[:2]
print(len(company)
for em in company1:
print(em)
#添加魔法函数以后增加了新的特性
3 python魔法函数一览
非数学运算
字符串表示:__repr__,__str__
集合序列相关:__len__,__getitem__,__setitem__,__delitem__,__contains__
迭代相关:__iter__,__next__
可调用:__call__
with上下文管理器:__enter__,__exit__
数值转换:__abs__,__bool__,__int__,__float__,__hash__,__index__,
元类相关:__new__,__init__
属性相关:__getattr__,__setattr__,__getattribute__,setattribute__,__dir__
属性描述:__get__,__set__,__delete__
协程:__await__,__aiter__,__anext__,__aenter__,__aexit__
class Comnpany(object):
def __init__(self,employee_list):
self.employee=employee_list
def __str__(self):
return ",".join(self.employee)
company =Company(["rom","bob","jane"])
#开发模式,默认会调用__repr__,__repr__可以写在任何模式下 __str__是在字符串格式化模式下会用,魔法函数定义了就不要调用它,python解释器知道什么时候调用它
company
数学运算
一元运算符:neg(-),pos(+),abs 二元运算符:it(<),le<=,eq==,ne!=,gt>,ge>= 算术运算符:add+,sub-,mul*,truediv/,ifoordiv//,mod%,__divmod__divmod(),pow**或pow(),__round__rou 反向运算符:rlshift,rrshift,rand,reor,ror 增量赋值位运算符:ilshift,irshift,iand,ixor,ior
class Nums(object):
def __init__(seif,num):
self.num=num
def __abs__(self):
return abs(self.num)
my_num= Nums(-1)
abs(my_num)
class MyVector(object):
def __init__(self,x,y)
self.x=x
self.y=y
def __add__(self,other_instance) :
re_vector=MyVector(self.x+other_instance(x),self.y+other_instance(y))
return re_vector
def __str__(self):
return "x:{x},y:{y}".format(x=self.x,y=self.y)
first_vec=MyVector(1,2)
second_vec=MyVector(2,3)
print(first_vec+second_vec)
4 len函数的特殊性
在使用的时候会隐含调用__len__方法,尽量使用原生的类型比如(list,dict..)
5 本章小结
什么是魔法函数,及特性,魔法函数是固定的,不用去定义它,例如__getitem__,python解释器内部做好了很多内置类型魔法函数,提高性能内部优化.