python 中常见的内置类型
什么是魔法函数?
python 的魔法函数总被双下划线包围, 它们可以给你的类增加特殊的方法. 如果你的对象实现了这些方法中的一个, 那么这个方法就会在特殊情况下被调用, 你可以定义想要
的行为, 而这一切都是自动发生的.
魔法函数一览
魔法函数举例
1.1.__getitem__
把对象变成可迭代的对象
例子:
- class Company(object):
- def __init__(self,employee_list):
- self.employee = employee_list
- #魔法函数, 给类加可迭代类型
- def __getitem__(self, item):
- return self.employee[item]
- company = Company(['11','22','33'])
- # 加了魔法函数 "__getitem__", 类就成了可迭代的了
- for em in company:
- print(em) #11,22,33
如果不用魔法函数循环出每个员工的方法
- class Company(object):
- def __init__(self,employee_list):
- self.employee = employee_list
- company = Company(['11','22','33'])
- 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(['11','22','33'])
- # 可以切片
- company1 = company[:2]
- # 可以判断 len 长度
- print(len(company1)) #2
- for em in company1:
- print(em) #11,22
- 1.2.__len__
- 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(["11", "22", "33"])
- # 如果不加魔法函数, len(company) 会报错的
- print(len(company)) #3
1.3. __repr__和__str__
1. 安装交互环境 (jupyter)
- pip install -i https://pypi.douban.com/simple ipython
- pip install -i https://pypi.douban.com/simple notebook
- # 启动
- ipython notebook
2.__repr__和__str__的用法
来源: https://www.cnblogs.com/derek1184405959/p/9005830.html