1. 什么是魔法函数
Python的类中有很多内置的魔法函数,他们以__开始和结束,如__init__,__str__等等,它是未来增强类的特性,不需要专门调用,在特定的场合下Python会自己调用,不能自己定义魔法函数
2. 常用的魔法函数
1. 字符串表示1. __str__:在print的情况下,可以返回友好的内容显示,python环境下直接运行返回指针地址
2. __repr__:不管是print或者直接执行,都会返回直接的内容显示
class Label: def __init__(self, value='hello world'): self.value = value label = Label() # 在cmd的python环境下才能输出,在py编辑器无输出 # 但他们都只是指向了一个地址,显然这不是我们想要的结果 lable # <__main__.Label at 0x2128207e448> print(label) # <__main__.Label object at 0x000002128207E448> # __str__:面向用户编程,在print下输出内容 class Label: def __init__(self, value='hello world'): self.value = value def __str__(self): return self.value label = Label() # __str__只能在print的情况下才能输出具体想要的效果 label # <__main__.Label at 0x212827fdcc8> print(label) # hello world # __repr__:面向程序员编程,不管是print还是直接运行的情况下,都能输出内容 class Label: def __init__(self, value='hello world'): self.value = value def __repr__(self): return self.value label = Label() # 输出结果直观 label # hello world print(label) # hello world
2. 集合序列相关
1. __len__: 计算对象容器中元素的个数
class Weekly: def __init__(self,my_list): self.my_list = my_list def __len__(self): return len(self.my_list) weekly = Weekly([1,2,3,4,5]) # 如果没有__len__函数,执行len方法时报错 print(len(weekly)) # 5
2.
class Weekly: def __init__(self,my_list): self.my_list = my_list def __len__(self): return len(self.my_list) weekly = Weekly([1,2,3,4,5]) # 如果没有__len__,执行len方法时报错 print(len(weekly)) # 5