一文了解 Python 的 “Magic” 方法

在之前的文章中,我聊过了Python的 __getitem__ 和 __setitem__ 方法。这些方法被称为“魔法”方法、特殊方法或者dunger方法(译者:国内书籍用“魔法”一词较多)。那么,什么是魔法方法呢?这正是今天咱们要说的内容。javascript

P.S.你会再一次的深深的爱上Python语言。java

也将是一篇较长的文章,来让咱们开始。express

魔法方法到底是什么?

魔法方法是一种具备特殊魅力的正常方法。Python经过这些魔法方法能够赋予你的class魔力。这些魔法方法都是以双下划线(__)做为前缀和后缀。坦率的讲,其实这些方法并无什么魔法,另外这些方法这Python的文档中也没有较为详细的介绍,所以,今天咱们就来详细的看一看这些方法。数据结构

魔法方法之初始化

全部的Python开发者都知道,__init__()是一个类(class)的第一个方法,也能够叫作构造函数。虽然,__init__()方法是第一个被建立的,可是它却不是第一个被调用的执行的,__new__()方法才是最先被调用的方法。less

  • __new__()方法:先读取参数,如:类名称,args,和kwargs。而后,__new__()方法把这些参数传递给对类名称的__init__()方法。 语法:__new__(class_name, args, kwargs)
  • __init__()方法:是类的初始化方法或构造方法,这也几乎用于全局的初始化目的。 语法:__init__(self, args, kwargs)
  • __del__()方法:类的析构函数。切记,这并非定义del x,而是定义了一个对象被垃圾回收的行为。 语法:__del__(self)

看一个例子:函数

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

  • __add__(self, other) 定义加法 (+)
  • __sub__(self, other) 定义减法 (-)
  • __mul__(self, other) 定义乘法 (*)
  • __floordiv__(self, other) 定义整除法 (//)
  • __div__(self, other) 定义浮点型除法 (/)
  • __mod__(self, other) 定义取余模运算 (%)
  • __and__(self, other) 定义按位与 (&)
  • __or__(self, other) 定义按位或 (|)
  • __xor__(self, other) 定义按位异或 (^)
  • __pow__(self, other) 定义指数运算 (**)
  • __lshift__(self, other) 定义按位左移 (<<)
  • __rshift__(self, other) 定义按位右移 (>>)

例如: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'

所以有的时候,你可能想写一些自自定义逻辑实现增量赋值操做。魔法方法支持的运算符有:对象

  • __iadd__(self, other) 定义加法 (+=)
  • __isub__(self, other) 定义减法 (-=)
  • __imul__(self, other) 定义乘法 (*=)
  • __ifloordiv__(self, other) 定义整除法 (//=)
  • __idiv__(self, other) 定义浮点型除法 (/=)
  • __imod__(self, other) 定义取模运算 (%=)
  • __iand__(self, other) 定义按位与 (&=)
  • __ior__(self, other) 定义按位或 (|=)
  • __ixor__(self, other) 定义按位异或(^=)
  • __ipow__(self, other) 定义指数运算 (**=)
  • __ilshift__(self, other) 定义按位左移 (<<=)
  • __irshift__(self, other) 定义按位右移 (>>=)

 

魔法方法之比较运算

Python有一组普遍的魔术方法实现比较。咱们能够覆盖默认的比较行为,来定义使用对象的引用方法。下面是比较魔法方法的列表:

  • __eq__(self, other) 帮助检查两个对象的相等。它定义了相等运算 (==)
  • __ne__(self, other) 定义了不等运算 (!=)
  • __lt__(self, other) 定义了小于运算 (<)
  • __gt__(self, other) 定义了大于运算 (>)
  • __le__(self, other) 定义了小于等于运算 (<=)
  • __ge__(self, other) 定义了大于等于运算 (>=)

例如:

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也关心你,哈哈!若是你想要自定义属于本身的方法,能够借助以下方法:

  • __int__(self) 定义类型转化为 int
  • __long__(self) 定义类型转化为 long
  • __float__(self) 定义类型转化为 float
  • __complex__(self) 定义类型转化为 complex(复数)
  • __oct__(self) 定义类型转化为 octal(八进制)
  • __hex__(self) 定义类型转化为 (十六进制)
  • __index__(self) 定义类型转化为一种int, 当对象被用于切片表达式( a slice expression)时

 

最经常使用的魔法方法

这里有一些魔法方法你应该常常遇到:

  • __str__(self) 定义了str()行为。例如,当你调用print(object_name),不管object_name是什么都会被__str__()执行
  • __repr__(self) 定义了repr()行为。这个很大程度上相似于__str__()。这两个之间的主要区别是,str()主要是人类可读的和repr()是机器可读的
  • __hash__(self) 定义了行为调用hash()
  • __len__(self) 返回容器的长度
  • __getitem__(self) 和 __setitem__(self). 更多内容能够详见我之前的博客文章。
  • __delitem__(self, key) 定义了一个删除一个项目的行为. 例如, del _list[3]
  • __iter__(self) 返回一个迭代容器
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 快乐!

相关文章
相关标签/搜索