python内置函数和魔法函数
内置方法:Python中声明每一个类系统都会加上一些默认内置方法,提供给系统调用该类的对象时使用。比如需要实例化一个对象时,需要调用该类的init方法;使用print去打印一个类时,其实调用的是str方法等等。
- init(self, …):初始化对象class,在创建新对象时调用。在方法里,可以初始化该对象的属性,否则调用其他时可能出“现has no attribute”错误;
- del(self):释放对象,在对象被虚拟机删除之前调用;
- new(cls,*args,**kwd):实例的生成操作,相比init在对象实例化调用做初始化,new方法运行在实例化阶段,修改某些实例化过程;
- str(self):在使用print语句时被调用,将对象的属性值拼接成字符串返回;
- getitem(self, key):获取序列的索引key对应的值,需要使用[]操作符的类需要覆盖的,等价于seq[key];
- setitem(self, key, value):类似geitem,需要seq[key]=value操作的类需要实现该方法;
- len(self):在调用内联函数len()时被调用;
- getattr(s, name): 获取属性的值;
- setattr(s, name, value):设置属性的值;
- delattr(s, name): 删除name属性;
- getattribute():getattribute()功能与getattr()类似,无条件被调用,通过实例访问属性。如果class中定义了getattr(),则getattr()不会被调用(除非显示调用或引发AttributeError异常);
- gt(self, other):判断self对象是否大于other对象;
- lt(self, other):判断self对象是否小于other对象;
- ge(slef, other):判断self对象是否大于或者等于other对象;
- le(self, other): 判断self对象是否小于或者等于other对象;
- eq(self, other):判断self对象是否等于other对象;
- call(self, *args): 把实例对象作为函数调用,在一个对象后面加上(),虚拟机就会调用该call方法。
内置变量:
- name:标识模块的名字的一个系统变量。假如当前模块是主模块(也就是调用其他模块的模块),那么此模块名字就是”main“,通过if判断这样就可以执行“main”后面的主函数内容;假如此模块是被import的,则此模块名字为文件名字(不加后面的.py),通过if判断这样就会跳过“main”后面的内容;
- file:用来获得模块所在的路径的,这可能得到的是一个相对路径;
- package:当前文件为None,导入其他文件,指定文件所在包用 . 分割;
- doc:文件注释
python英文官方文档详细说明:点击查看
魔法函数
Python进阶:实例讲解Python中的魔法函数(Magic Methods)
定制类和魔法方法
- 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)
python内置函数和魔法函数的更多相关文章
- Python内置的字符串处理函数整理
Python内置的字符串处理函数整理 作者: 字体:[增加 减小] 类型:转载 时间:2013-01-29我要评论 Python内置的字符串处理函数整理,收集常用的Python 内置的各种字符串处理 ...
- python内置常用高阶函数(列出了5个常用的)
原文使用的是python2,现修改为python3,全部都实际输出过,可以运行. 引用自:http://www.cnblogs.com/duyaya/p/8562898.html https://bl ...
- Python内置进制转换函数(实现16进制和ASCII转换)
在进行wireshark抓包时你会发现底端窗口报文内容左边是十六进制数字,右边是每两个十六进制转换的ASCII字符,这里使用Python代码实现一个十六进制和ASCII的转换方法. hex() 转换一 ...
- Python内置的字符串处理函数
生成字符串变量 str='python String function' 字符串长度获取:len(str) 例:print '%s length=%d' % (str,len(str)) 连接字符 ...
- Python 内置的一些高效率函数用法
1. filter(function,sequence) 将sequence中的每个元素,依次传进function函数(可以自定义,返回的结果是True或者False)筛选,返回符合条件的元素,重组 ...
- Python内置函数系列
Python内置(built-in)函数随着python解释器的运行而创建.在Python的程序中,你可以随时调用这些函数,不需要定义. 作用域相关(2) locals() :以字典类型返回当前位置 ...
- Python内置高阶函数map()
map()函数map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回. 例如,对于lis ...
- python内置函数
python内置函数 官方文档:点击 在这里我只列举一些常见的内置函数用法 1.abs()[求数字的绝对值] >>> abs(-13) 13 2.all() 判断所有集合元素都为真的 ...
- python 内置函数和函数装饰器
python内置函数 1.数学相关 abs(x) 取x绝对值 divmode(x,y) 取x除以y的商和余数,常用做分页,返回商和余数组成一个元组 pow(x,y[,z]) 取x的y次方 ,等同于x ...
随机推荐
- 2017 Bangladesh National High School Programming Contest ( National Round, Senior Group ), NHSPC 2017 题解
[题目链接] A. Charm Is Not Always Enough 模拟一下就可以了. #include <bits/stdc++.h> using namespace std; i ...
- 命令:which、whereis、who和w
开始 命令搜索的顺序 在shell function中查找,有则调用,无则下一步: 判断命令是否为bash内置命令,有则调用,无则下一步: 在$PATH中搜索该命令,有则调用,无则报错. 判断命令类型 ...
- 使用Mongo索引需要注意的几个点
1.正则表达式和取反运算符不适合建立索引 正则表达式:$regex 取反运算符:$ne ,$nin 2.backgroud建立索引速度缓慢 前台创建是会有阻塞,backgroud效率缓慢,实际情况实际 ...
- HTML基础-DAY1
HTML基础 Web的本质就是利用浏览器访问socket服务端,socket服务端收到请求回复数据提供给浏览器进行渲染显示. import socket def main(): sock = sock ...
- Xamarin 2017.10.9更新
Xamarin 2017.10.9更新 本次更新主要解决了一些bug.Visual Studio 2017升级到15.4获得新功能.Visual Studio 2015需要工具-选项-Xamarin ...
- Python复数属性和方法操作实例
转自: https://blog.csdn.net/henni_719/article/details/56665254 #coding=utf8 ''' 复数是由一个实数和一个虚数组合构成,表示为: ...
- DataTable,List,Dictonary互转,筛选及相关写法
1.创建自定义DataTable /// 创建自定义DataTable(一) 根据列名字符串数组, /// </summary> /// <param name="sLi ...
- 命令神器:lsof 常用
lsof -i 显示所有网络连接lsof -i 6 获取IPv6信息lsof -itcp 显示tcp连接lsof -i:80 显示指定端口信息lsof -i@172.12.5.6 显示指定ip连接ls ...
- zookeeper【5】分布式锁
我们常说的锁是单进程多线程锁,在多线程并发编程中,用于线程之间的数据同步,保护共享资源的访问.而分布式锁,指在分布式环境下,保护跨进程.跨主机.跨网络的共享资源,实现互斥访问,保证一致性. 架构图: ...
- 持续集成之Jenkins插件使用(一)- 多个job之间的串并联
转载自:http://qa.blog.163.com/blog/static/190147002201391661510655/ Jenkins除了开源和免费,还有一个最吸引人的功能之一就是支持插件. ...