3-1 什么是魔法函数
3.1节源代码合集
第一部分:
class Company(object):
def __init__(self, employee_list):
self.employee = employee_list
company = Company(["tom", "bob", "jane"])
for em in company.employee :
print(em)
第二部分:魔法函数,双下划线开头,双下划线结尾,只能是使用内置的,不能自己定义,用于增强特性:
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 em in company : #使得对象可迭代了
print(em)
3.2节:3-2 python数据模型对python的影响
加入魔法函数后,对python本身的语法结构也是有影响的
3.2代码:
class Company(object):
def __init__(self, employee_list):
self.employee = employee_list
def __len__(self):
return len(self.employee)
company = Company(["tom", "bob", "jane"])
print(len(company)) #对象有长度了,也可以切片了
3-3 python魔法函数一览
python会默认调用魔法函数
3-3-1非数学运算
不调用,只写company也是等效的
3-3-2数学运算
3-4,len函数的特殊性
主要讲了,使用python内置list,set,dic等原生结构效率更高,是直接读取数据,而不是循环