内置函数,工厂函数和魔法函数
内置函数,工厂函数 和 魔法函数
内置函数 (Built-in Functions)

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:文件注释
1
2
3
4>>> print.__name__
'print'
>>> print.__doc__
"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\nPrints the values to a stream, or to sys.stdout by default.\nOptional keyword arguments:\nfile: a file-like object (stream); defaults to the current sys.stdout.\nsep: string inserted between values, default a space.\nend: string appended after the last value, default a newline.\nflush: whether to forcibly flush the stream."
1 | |
工厂函数
python2.2 之后,将类和类型进行了统一,做法就是将如下的类型 内置函数 转换成 工厂函数
1
int(),float(), bool(), str(), list(),tuple(), type(), dict(), set(), frozenset()工厂函数,就是能够产生类实例的内置函数
1
2
3
4
5
6
7
8
9
10
11# 普通的内置函数
>> type(len)
>> <class 'builtin_function_or_method'>
>> type(open)
>> <class 'builtin_function_or_method'>
# 工厂函数,就是能够产生类实例的**内置函数**
>> type(int)
>> <class 'type'>
>> type(list)
>> <class 'type'>工厂函数看上去有点像函数,实质上他们是类,当你调用它们时,实际上是生成了该类型的一个实例,就像工厂生产货物一样.
1
2
3
4
5
6
7
8
9
10>>> type(int)
<class 'type'>
>>> type(list)
<class 'type'>
>>>
>>> class C:
... pass
...
>>> type(C)
<class 'type'>一个类定义完成就变成了类对象,所以工厂函数其实就是类对象
1
2
3
4
5
6
7# 实例化int 对象,传入相应的参数
>>> a = int('123')
>>> b = int('456')
# 实例对象还可以计算
>>> a + b
579python的魔法方法还可以自定义对象的数值处理,通过对魔法方法的重写,可以自定义任何对象间的算术运算
add(self, other) 定义加法的行为:+ sub(self, other) 定义减法的行为:- mul(self, other) 定义乘法的行为:* truediv(self, other) 定义真除法的行为:/ floordiv(self, other) 定义整数除法的行为:// mod(self, other) 定义取模算法的行为:% divmod(self, other) 定义当被 divmod() 调用时的行为,divmod(a, b)返回一个元组:(a//b, a%b) pow(self, other[, modulo]) 定义当被 power() 调用或 ** 运算时的行为 lshift(self, other) 定义按位左移位的行为:<< rshift(self, other) 定义按位右移位的行为:>> and(self, other) 定义按位与操作的行为:& xor(self, other) 定义按位异或操作的行为:^ or(self, other) 定义按位或操作的行为:| 1
2
3
4
5
6
7
8
9
10
11
12
13
14>>> class New_int(int):
def __add__(self, other):
return int.__sub__(self, other)
def __sub__(self, other):
return int.__add__(self, other)
>>> a = New_int(3)
>>> b = New_int(5)
>>> a + b
-2
>>> a - b
8
魔法方法
魔法方法都是被双下划线包围
__init__(self, param1, param2...)对象创建完后,在初始化实例对象时,该魔法方法会自动调用。可以根据需要自行改写该方法:
1
2
3
4
5
6
7
8
9>>> class Ball:
... def __init__(self, name):
... self.name = name
... def kick(self):
... print('my name is %s, fuck, who kick me#@#' % self.name)
...
>>> c = Ball('土豆')
>>> c.kick()
my name is 土豆, fuck, who kick me#@#魔法方法是面向对象的python的一切,如果你不知道魔法方法,说明你还没能意识到面向对象的python的强大
魔法方法的“魔力”体现在他们总是能够在适当的时候被调用
Python中每个魔法函数都对应了一个Python内置函数或操作,比如__str__对应str函数,__lt__对应小于号<等。Python中的魔法函数可以大概分为以下几类:
类的构造、删除:
1 | |
二元操作符:
1 | |
扩展二元操作符:
1 | |
一元操作符:
1 | |
比较函数:
1 | |
类的表示、输出:
1 | |
类容器:
1 | |