本文为 AI 研习社编译的技术博客,原标题 : Python magic methods or special methods 翻译 | 邓普斯•杰弗 校对 | 酱番梨 整理 | 菠萝妹
在以前的文章中,我聊过了Python的 __getitem__ 和 __setitem__ 方法。这些方法被称为“魔法”方法、特殊方法或者dunger方法(译者:国内书籍用“魔法”一词较多)。那么,什么是魔法方法呢?这正是今天我们要说的内容。
P.S.你会再一次的深深的爱上Python语言。
也将是一篇较长的文章,来让我们开始。
魔法方法是一种具有特殊魅力的正常方法。Python通过这些魔法方法可以赋予你的class魔力。这些魔法方法都是以双下划线(__)作为前缀和后缀。坦率的讲,其实这些方法并没有什么魔法,另外这些方法这Python的文档中也没有较为详细的介绍,因此,今天我们就来详细的看一看这些方法。
所有的Python开发者都知道,__init__()是一个类(class)的第一个方法,也可以叫做构造函数。虽然,__init__()方法是第一个被创建的,但是它却不是第一个被调用的执行的,__new__()方法才是最早被调用的方法。
看一个例子:
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)拼接。类似这种的有趣行为,我们可以通过魔法方法的算术运算实现定义。
例如:
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不仅允许我们定义算术运算,也允许我们定义增量赋值运算。如果你不知道什么是增量赋值是什么?那么我们来看一个简单的例子:
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 快乐!