魔法函数

  • python中以双下划线开始和结束的函数(不可自己定义)为魔法函数
  • 调用类实例化的对象的方法时自动调用魔法函数(感觉不需要显示调用的函数都叫)
  • 在自己定义的类中,可以实现之前的内置函数,比如下面比较元素sorted时用It函数(lt(self, other):判断self对象是否小于other对象;)
class MyVector(object):
def __init__(self, x, y):
self.x = x
self.y = y def __add__(self, other_instance):
re_vector = MyVector(self.x+other_instance.x, self.y+other_instance.y)
return re_vector def __str__(self):
return"x:{x}, y:{y}".format(x=self.x, y=self.y) first_vec = MyVector(1,2)
second_vec = MyVector(2,3)
print(first_vec+second_vec)

操作符重载:通过定义类的一些约定的以"__"开头并结尾的函数,可以到达重载一些特定操作的目的

__str__ / __unicode__       
当print一个对象实例时,实际是print该实例 .str()函数的返回值:

class A:
def __str__(self):
return "A"
def __unicode__(self):
return "uA"

魔法函数有什么作用?

魔法函数可以为你写的类增加一些额外功能,方便使用者理解。举个简单的例子,我们定义一个“人”的类People,当中有属性姓名name、年龄age。让你需要利用sorted函数对一个People的数组进行排序,排序规则是按照name和age同时排序,即name不同时比较name,相同时比较age。由于People类本身不具有比较功能,所以需要自定义,你可以这么定义People类:

class People(object):
def __init__(self, name, age):
self.name = name
self.age = age
return def __str__(self):
return self.name + ":" + str(self.age) def __lt__(self, other):
return self.name < other.name if self.name != other.name else self.age < other.age if __name__=="__main__": print("\t".join([str(item) for item in sorted([People("abc", 18), People("abe", 19), People("abe", 12), People("abc", 17)])]))
  • 上个例子中的__lt__函数即less than函数,即当比较两个People实例时自动调用。

Python中有哪些魔法函数?

Python中每个魔法函数都对应了一个Python内置函数或操作,比如__str__对应str函数,__lt__对应小于号<等。Python中的魔法函数可以大概分为以下几类:

类的构造、删除:

object.__new__(self, ...)
object.__init__(self, ...)
object.__del__(self)

二元操作符:

+	object.__add__(self, other)
- object.__sub__(self, other)
* object.__mul__(self, other)
// object.__floordiv__(self, other)
/ object.__div__(self, other)
% object.__mod__(self, other)
** object.__pow__(self, other[, modulo])
<< object.__lshift__(self, other)
>> object.__rshift__(self, other)
& object.__and__(self, other)
^ object.__xor__(self, other)
| object.__or__(self, other)

扩展二元操作符:

+=	object.__iadd__(self, other)
-= object.__isub__(self, other)
*= object.__imul__(self, other)
/= object.__idiv__(self, other)
//= object.__ifloordiv__(self, other)
%= object.__imod__(self, other)
**= object.__ipow__(self, other[, modulo])
<<= object.__ilshift__(self, other)
>>= object.__irshift__(self, other)
&= object.__iand__(self, other)
^= object.__ixor__(self, other)
|= object.__ior__(self, other)

一元操作符:

-	object.__neg__(self)
+ object.__pos__(self)
abs() object.__abs__(self)
~ object.__invert__(self)
complex() object.__complex__(self)
int() object.__int__(self)
long() object.__long__(self)
float() object.__float__(self)
oct() object.__oct__(self)
hex() object.__hex__(self)
round() object.__round__(self, n)
floor() object__floor__(self)
ceil() object.__ceil__(self)
trunc() object.__trunc__(self)

比较函数:

<	object.__lt__(self, other)
<= object.__le__(self, other)
== object.__eq__(self, other)
!= object.__ne__(self, other)
>= object.__ge__(self, other)
> object.__gt__(self, other)

类的表示、输出:

str()	object.__str__(self)
repr() object.__repr__(self)
len() object.__len__(self)
hash() object.__hash__(self)
bool() object.__nonzero__(self)
dir() object.__dir__(self)
sys.getsizeof() object.__sizeof__(self)

类容器:

len()	object.__len__(self)
self[key] object.__getitem__(self, key)
self[key] = value object.__setitem__(self, key, value)
del[key] object.__delitem__(self, key)
iter() object.__iter__(self)
reversed() object.__reversed__(self)
in操作 object.__contains__(self, item)
字典key不存在时 object.__missing__(self, key)

PythonStudy——魔法函数 Magic Methods的更多相关文章

  1. 如何在Python中快速画图——使用Jupyter notebook的魔法函数(magic function)matplotlib inline

    如何在Python中快速画图--使用Jupyter notebook的魔法函数(magic function)matplotlib inline 先展示一段相关的代码: #we test the ac ...

  2. jupyter|魔法函数问题| UsageError: Line magic function `%` not found

    问题: jupyter notebook 使用魔法函数% matplotlib inline,报错:UsageError: Line magic function `%` not found 解决: ...

  3. Python魔法方法(magic method)细解几个常用魔法方法(上)

    这里只分析几个可能会常用到的魔法方法,像__new__这种不常用的,用来做元类初始化的或者是__init__这种初始化使用的 每个人都会用的就不介绍了. 其实每个魔法方法都是在对内建方法的重写,和做像 ...

  4. python内置函数和魔法函数

    内置方法:Python中声明每一个类系统都会加上一些默认内置方法,提供给系统调用该类的对象时使用.比如需要实例化一个对象时,需要调用该类的init方法:使用print去打印一个类时,其实调用的是str ...

  5. php-18个魔法函数

    目录 php魔法函数 介绍 范例 1.__construct() 2.__destruct() 3.__call() 4.__callStatic 5.__get() 6.__set() 7.__is ...

  6. php使用魔法函数和不使用魔法函数比较

    /** * use magic 0.31868386268616s * not use magic 0.11876797676086s */ class Test { private $varstr ...

  7. A Guide to Python's Magic Methods

    Book Source:[https://rszalski.github.io/magicmethods/] magic methods: 名称前后有双下划线的方法 构造函数和初始化 初始化类实例时, ...

  8. Pthon魔术方法(Magic Methods)-描述器

    Pthon魔术方法(Magic Methods)-描述器 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.描述器概述 1>.描述器定义 Python中,一个类实现了&quo ...

  9. Pthon魔术方法(Magic Methods)-反射

    Pthon魔术方法(Magic Methods)-反射 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.反射概述 运行时,区别于编译时,指的时程序被加载到内存中执行的时候. 反射 ...

随机推荐

  1. _mount_allowed

    该表配置可以坐骑的使用区域,可能需要修改spell.dbc,允许在室内等特殊区域使用坐骑技能

  2. GitHub的Windows客户端的使用教程

    GitHub for Windows客户端的使用教程 什么是Github >说到什么是GitHub,我们先看wikipedia的描述“GitHub是一个利用Git进行版本控制.专门用于存放软件代 ...

  3. loadrunner中web_reg_save_param和web_reg_save_param_ex的区别

    在使用Loadrunner进行性能测试,编写接口请求脚本时,通过会用到关联函数,而web_reg_save_param和web_reg_save_param_ex的函数有什么区别呢?以下为总结的两点, ...

  4. 高并发情况下Linux系统及kernel参数优化

    众所周知在默认参数情况下Linux对高并发支持并不好,主要受限于单进程最大打开文件数限制.内核TCP参数方面和IO事件分配机制等.下面就从几方面来调整使Linux系统能够支持高并发环境. Iptabl ...

  5. vue中关于v-for性能优化---track-by属性

    vue中关于v-for性能优化---track-by属性 最近看了一些react,angular,Vue三者的对比文章,对比来说Vue比较突出的是轻量级与易上手. 对比Vue与angular,Vue有 ...

  6. [poj P1475] Pushing Boxes

    [poj P1475] Pushing Boxes Time Limit: 2000MS   Memory Limit: 131072K   Special Judge Description Ima ...

  7. MapReduce(五)

    MapReduce的(五) 1.MapReduce的多表关联查询. 根据文本数据格式.查询多个文本中的内容关联.查询. 2.MapReduce的多任务窜执行的使用 多任务的串联执行问题,主要是要建立c ...

  8. web项目执行流程

    先扫描web.xml文件 jsp请求servlet servlet  调数据/不调数据 重定向/转发       Dao(封装数据)   Biz(数据处理)     逻辑判段 返回前端界面显示

  9. linux c使用socket进行http 通信,并接收任意大小的http响应(一)

    如何进行http通信呢?我们打开任意一个浏览器,按F12,再选择网络,然后打开任意一个网站,我们就可以看到浏览器和网站通信的过程 如下图: 然后,我们任意点击一条记录,可以看到 然后,查找http协议 ...

  10. 查看apk文件包名的一些方法

    1,如果有源码 直接将apk包修改为zip,并解压找到AndroidManifest.xml文件,在文件中搜索“package”找到相应的包名 2,使用adb命令 前提是已经下载android SDK ...