1. 什么是魔法函数
魔法函数即 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", "Jerry", "Bob"])
# 没有__getitem__时,通过这种形式遍历 Company 类中的 employee
for em in company.employee:
print(em)
# 自定义__getitem__后,Company 变为可迭代对象
for em in company:
print(em)
代码中的__init__、__getitem__即为魔法函数
2.Python 的数据模型以及数据模型对 Python 的影响
魔法函数自身是 Python 的数据模型,魔法函数是网络风行的叫法
以__len__为例阐明数据模型(魔法函数)对 Python 的影响
class Company(object):
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", "Jerry", "Bob"])
# 不定义__len__是无奈应用 len()的
print(len(company))
3.Python 魔法函数一览(个别阐明)
3.1 非数学运算
字符串示意__repr__、__str__
- __str__:对对象进行字符串格式化
class Company(object):
def __init__(self, employee_list):
self.employee = employee_list
company = Company(["Tom", "Jerry", "Bob"])
print(company) # 在 Python 解释器中会隐含调用 str, 即 print(str(company))
此时输入:<__main__.Company object at 0x000001D53A322D30>
验证解释器隐含调用 str
class Company(object):
def __init__(self, employee_list):
self.employee = employee_list
def __str__(self):
return ','.join(self.employee)
company = Company(["Tom", "Jerry", "Bob"])
print(company)
输入:Tom,Jerry,Bob
- __repr__: 开发模式才会用到
class Company(object):
def __init__(self, employee_list):
self.employee = employee_list
company = Company(["Tom", "Jerry", "Bob"])
company # 在 Python 解释器中会隐含调用 repr, 即 repr(company), 在 Python 外部为 company.__repr__()
此时输入:<__main__.Company at 0x1d53a2d3a58>
验证解释器隐含调用 repr
class Company(object):
def __init__(self, employee_list):
self.employee = employee_list
def __repr__(self):
return ','.join(self.employee)
company = Company(["Tom", "Jerry", "Bob"])
company
输入:Tom,Jerry,Bob
3.2 数学运算
- pass