第十七天学习python

相关魔法方法总结

基本魔法方法
功能
new(cls[, …])
1. new 是在一个对象实例化的时候所调用的第一个方法 2. 它的第一个参数是这个类,其他的参数是用来直接传递给 init 方法 3. new 决定是否要使用该 init 方法,因为 new 可以调用其他类的构造方法或者直接返回别的实例对象来作为本类的实例,如果 new 没有返回实例对象,则 init 不会被调用 new 主要是用于继承一个不可变的类型比如一个 tuple 或者 string
init(self[, …])
构造器,当一个实例被创建的时候调用的初始化方法
del(self)
析构器,当一个实例被销毁的时候调用的方法
call(self[, args…])
允许一个类的实例像函数一样被调用:x(a, b) 调用 x.call(a, b)
len(self)
定义当被 len() 调用时的行为
repr(self)
定义当被 repr() 调用时的行为
bytes(self)
定义当被 bytes() 调用时的行为
str(self)
定义当被 str() 调用时的行为
hash(self)
定义当被 hash() 调用时的行为
bool(self)
定义当被 bool() 调用时的行为,应该返回 True 或 False
format(self, format_spec)
定义当被 format() 调用时的行为

属性相关魔法方法
功能
getattr(self, name)
定义当用户试图获取一个不存在的属性时的行为
getattribute(self, name)
定义当该类的属性被访问时的行为
setattr(self, name, value)
定义当一个属性被设置时的行为
delattr(self, name)
定义当一个属性被删除时的行为
dir(self)
定义当 dir() 被调用时的行为
get(self, instence, owner)
定义当描述符的值被取得时的行为
set(self, instence, value)
定义当描述符的值被改变时的行为
delete(self, instence)
定义当描述符的值被删除时的行为

算数运算魔法方法
功能
add(self, other)
定义加法的行为:+
sub(self, other)
定义减法的行为:-
mul(self, other)
定义乘法的行为:*
truediv(self, other)
定义真除法的行为:/
floordiv(self, other)
定义整数除法的行为://
mod(self, other)
定义取模算法的行为:%
divmod(self, other)
定义当被 divmod() 调用时的行为
pow(self, other[, modulo])
定义当被 power() 调用或 ** 运算时的行为
lshift(self, other)
定义按位左移位的行为:<<
rshift(self, other)
定义按位右移位的行为:>>
and(self, other)
定义按位与操作的行为:&
xor(self, other)
定义按位异或操作的行为:^
or(self, other)
定义按位或操作的行为:\

类型转换魔法方法
功能
complex(self)
定义当被 complex() 调用时的行为(需要返回恰当的值)
int(self)
定义当被 int() 调用时的行为(需要返回恰当的值)
float(self)
定义当被 float() 调用时的行为(需要返回恰当的值)
round(self[, n])
定义当被 round() 调用时的行为(需要返回恰当的值)
index(self)
当对象是被应用在切片表达式中时,实现×××强制转换 2. 如果你定义了一个可能在切片时用到的定制的数值型,你应该定义 index 3. 如果 index 被定义,则 int 也需要被定义,且返回相同的值

容器相关魔法方法
功能
len(self)
定义当被 len() 调用时的行为(返回容器中元素的个数)
getitiem(self, key)
定义获取容器中指定元素的行为,相当于 self[key]
setitem(self, key, value)
定义设置容器中指定元素的行为,相当于 self[key] = value
delitem(self, key)
定义删除容器中指定元素的行为,相当于 del self[key]
iter(self)
定义当迭代容器中的元素的行为
reversed(self)
定义当被 reversed() 调用时的行为
contains(self, item)
定义当使用成员测试运算符(in 或 not in)时的行为

猜你喜欢

转载自blog.csdn.net/qq_40594554/article/details/81633559