什么是魔法函数?
1)在python中以双下滑线开头并且以双下滑线结尾的函数
2)魔法函数可以随意定义某个类的特性,这些方法在进行特定的操作时会自动被调用
普通的遍历
class Company(object):
def __init__(self, employee_list):
self.employee = employee_list
company = Company(["tom", "bob", "jane"])
emploee = company.employee
for em in emploee:
print(em)
运行结果
实现 getitem (变为可迭代类型)
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)
运行结果
Python的数据模型以及数据模型对Python的影响
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"])
company1 = company[:2]
for em in company1:
print(em)
也可利用 __getitem__成为序列类型,使用切片
实现__len__获取长度
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魔法函数一览
原文:https://www.cnblogs.com/loongll/p/11286188.html