在之前的文章中,我聊过了Python的 __getitem__ 和 __setitem__ 方法。这些方法被称为“魔法”方法、特殊方法或者dunger方法(译者:国内书籍用“魔法”一词较多)。那么,什么是魔法方法呢?这正是今天咱们要说的内容。javascript
P.S.你会再一次的深深的爱上Python语言。java
也将是一篇较长的文章,来让咱们开始。express
魔法方法是一种具备特殊魅力的正常方法。Python经过这些魔法方法能够赋予你的class魔力。这些魔法方法都是以双下划线(__)做为前缀和后缀。坦率的讲,其实这些方法并无什么魔法,另外这些方法这Python的文档中也没有较为详细的介绍,所以,今天咱们就来详细的看一看这些方法。数据结构
全部的Python开发者都知道,__init__()是一个类(class)的第一个方法,也能够叫作构造函数。虽然,__init__()方法是第一个被建立的,可是它却不是第一个被调用的执行的,__new__()方法才是最先被调用的方法。less
看一个例子:函数
class SimpleInit(object): ''' Class to initialize a list with a value ''' def __init__(self, value=10): self._list = [value] def __del__(self): del self._list
算术运算是很是常见的,所以,若是你想建立属于本身的数据结构,魔法方法会使你的实现更容易。例如:咱们能够像这样,some_list + some_list2,实现Python的列表(list)拼接。相似这种的有趣行为,咱们能够经过魔法方法的算术运算实现定义。spa
例如:code
class SimpleAdder(object): def __init__(self, elements=[]): self._list = elements def __add__(self, other): return self._list + other._list def __str__(self): return str(self._list) a = SimpleAdder(elements=[1,2,3,4])b = SimpleAdder(elements=[2, 3, 4])print(a + b) # [1, 2, 3, 4, 2, 3, 4]
Python不只容许咱们定义算术运算,也容许咱们定义增量赋值运算。若是你不知道什么是增量赋值是什么?那么咱们来看一个简单的例子:orm
x = 5 x += 1 # This first adds 5 and 1 and then assigns it back to 'x'
所以有的时候,你可能想写一些自自定义逻辑实现增量赋值操做。魔法方法支持的运算符有:对象
Python有一组普遍的魔术方法实现比较。咱们能够覆盖默认的比较行为,来定义使用对象的引用方法。下面是比较魔法方法的列表:
例如:
class WordCounter(object): ''' Simple class to count number of words in a sentence ''' def __init__(self, sentence): # split the sentence on ' ' if type(sentence) != str: raise TypeError('The sentence should be of type str and not {}'.format(type(sentence))) self.sentence = sentence.split(' ') self.count = len(self.sentence) def __eq__(self, other_class_name): ''' Check the equality w.r.t length of the list with other class ''' return self.count == other_class_name.count def __lt__(self, other_class_name): ''' Check the less-than w.r.t length of the list with other class ''' return self.count < other_class_name.count def __gt__(self, other_class_name): ''' Check the greater-than w.r.t length of the list with other class ''' return self.count > other_class_name.count word = WordCounter('Omkar Pathak')print(word.count)
不少时候开发人员须要隐性的转换变量类型,来知足最要想要的结果。Python是关心你内在数据的类型的一种动态类型语言,除此以外,Python也关心你,哈哈!若是你想要自定义属于本身的方法,能够借助以下方法:
这里有一些魔法方法你应该常常遇到:
class CustomList(object): def __init__(self, elements=0): self.my_custom_list = [0] * elements def __str__(self): return str(self.my_custom_list) def __setitem__(self, index, value): self.my_custom_list[index] = value def __getitem__(self, index): return "Hey you are accessing {} element whose value is: {}".format(index, self.my_custom_list[index]) def __iter__(self): return iter(self.my_custom_list)obj = CustomList(12)obj[0] = 1print(obj[0])print(obj)
把这些有魔法的Python礼物送给你!!
coding 快乐!