一. 什么是魔法函数
# 打印class里的list
class Company:
def __init__(self, employee_list):
self.employee = employee_list
company = Company(['Alice', 'Bob', 'Candy'])
for x in company.employee:
print(x) # 'Alice', 'Bob', 'Candy'
# for x in company:
# print(x)
# TypeError: 'Company' object is not iterable
# 直接遍历class
class Company:
def __init__(self, employee_list):
self.employee = employee_list
# 添加魔法函数:__getitem__
def __getitem__(self, item):
return self.employee[item]
company = Company(['Alice', 'Bob', 'Candy'])
for x in company:
print(x) # 'Alice', 'Bob', 'Candy'
# for x in company[1:]: 切片
# print(x) # 'Bob', 'Candy'
# print(len(company)) # TypeError: object of type 'Company' has no len()
print(len(company[:])) # 3,Company并未实现len函数所以直接调用len会出错
# 但是company[:]是先进行切片,切片后会变成list类型,因此可以用len函数
# 长度魔法函数
class Company:
def __init__(self, employee_list):
self.employee = employee_list
# 添加魔法函数:__getitem__
def __getitem__(self, item):
return self.employee[item]
def __len__(self):
return len(self.employee)
company = Company(['Alice', 'Bob', 'Candy'])
print(len(company))
二. python的数据模型以及数据模型对python的影响(数据模型也叫魔法函数)
三. 魔法函数一览
image.png
# 打印对象,打印对象时,python会默认调用str()函数
class Company:
def __init__(self, employee_list):
self.employee = employee_list
company = Company(['Alice', 'Bob', 'Candy'])
print(company) # <__main__.Company object at 0x000001E264E0FE80>
print(str(company)) # <__main__.Company object at 0x000001E264E0FE80>
# __str__与__repr__的区别
# 使用__str__
class Company:
def __init__(self, employee_list):
self.employee = employee_list
def __str__(self):
return ','.join(self.employee)
company = Company(['Alice', 'Bob', 'Candy'])
print(company) # Alice,Bob,Candy
company # <__main__.Company at 0x1e264ee1cc0>
# 使用__repr__:开发时调用
class Company:
def __init__(self, employee_list):
self.employee = employee_list
def __repr__(self):
return ','.join(self.employee)
company = Company(['Alice', 'Bob', 'Candy'])
print(company) # Alice,Bob,Candy
company # Alice,Bob,Candy
# 数值魔法函数
class Num:
def __init__(self, x, y):
self.x = x
self.y = y
# def __abs__(self):
# return abs(self.num)
def __add__(self, other_instance):
re_vactor = Num(self.x + other_instance.x, self.y + other_instance.y)
return re_vactor
def __str__(self):
return 'x: {x}, y: {y}'.format(x=self.x, y=self.y)
num1 = Num(2, 3)
num2 = Num(1, 4)
print(num1 + num2) # x: 3, y: 7
在cpython中,内置类型如:
list
,dict
,set
都是用C语言实现的,所以在用len
方法时会更快,而自己写的类实现的魔法函数__len__
,其实是对对象进行了遍历,没有原生的内置类型快,因此要尽量用python的内置类型