python 魔法方法诠释

什么是Python魔法方法    

什么是魔法方法呢?它们在面向对象的Python的处处皆是。它们是一些可以让你对类添加“魔法”的特殊方法。 它们经常是两个下划线包围来命名的(比如 init, lt )。但是现在没有很好的文档来解释它们。 所有的魔法方法都会在Python的官方文档中找到,但是它们组织松散。而且很少会有示例(有的是无聊的语法描述, 语言参考)。    

 魔法方法就如同它的名字一样神奇,总能在你需要的时候为你提供某种方法来让你的想法实现。魔法方法是指Python内部已经包含的,被双下划线所包围的方法,这些方法在进行特定的操作时会自动被调用,它们是Python面向对象下智慧的结晶。初学者掌握Python的魔法方法也就变得尤为重要了。    

为什么要使用Python魔法方法    

 使用Python的魔法方法可以使Python的自由度变得更高,当不需要重写时魔法方法也可以在规定的默认情况下生效,在需要重写时也可以让使用者根据自己的需求来重写部分方法来达到自己的期待。而且众所周知Python是支持面向对象的语言Python的基本魔法方法就使得Python在面对对象方面做得更好。    

魔法方法名    

说明    

基础魔法方法(较为常用)        

new(cls[, ...])    

1.实例化对象时第一个被调用的方法

2.其参数直接传递给init方法处理    

3.我们一般不会重写该方法  


init(self[, ...])    构造方法,初始化类的时候被调用

del(self)    析构方法,当实例化对象被彻底销毁时被调用(实例化对象的所有指针都被销毁时被调用)

call(self[, args...])    允许一个类的实例像函数一样被调用:x(a, b) 调用 x.call(a, b)

len(self)    定义当被 len() 调用时的行为

repr(self)    定义当被 repr() 调用时的行为

str(self)    定义当被 str() 调用时的行为

bytes(self)    定义当被 bytes() 调用时的行为

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, instance, owner)    定义当描述符的值被取得时的行为

set(self, instance, value)    定义当描述符的值被改变时的行为

delete(self, instance)    定义当描述符的值被删除时的行为

 比较操作符


lt(self, other)    定义小于号的行为:x < y 调用 x.lt(y)

le(self, other)    定义小于等于号的行为:x <= y 调用 x.le(y)

eq(self, other)    定义等于号的行为:x == y 调用 x.eq(y)

ne(self, other)    定义不等号的行为:x != y 调用 x.ne(y)

gt(self, other)    定义大于号的行为:x > y 调用 x.gt(y)

ge(self, other)    定义大于等于号的行为:x >= y 调用 x.ge(y)

 算数运算符|


def __add__(self, other):    # 定义加法的行为:+
def __sub__(self, other):    # 定义减法的行为:-
def __mul__(self, other):    # 定义乘法的行为:*
def __truediv__(self, other):    # 定义真除法的行为:/
def __floordiv__(self, other):    # 定义整数除法的行为://
def __mod__(self, other):    # 定义取模算法的行为:%
def __divmod__(self, other):    # 定义当被 divmod() 调用时的行为
def __pow__(self, other[, modulo]):    # 定义当被 power() 调用或 ** 运算时的行为
def __lshift__(self, other):    # 定义按位左移位的行为:<<
def __rshift__(self, other):    # 定义按位右移位的行为:>>
def __and__(self, other):    # 定义按位与操作的行为:&
def __xor__(self, other):    # 定义按位异或操作的行为:^
def __or__(self, other):    # 定义按位或操作的行为:

反运算(类似于运算方法)


radd(self, other)     当被运算对象(左边的操作对象)不支持该运算时被调用

rsub(self, other)     当被运算对象(左边的操作对象)不支持该运算时被调用

rmul(self, other)     当被运算对象(左边的操作对象)不支持该运算时被调用

rtruediv(self, other)     当被运算对象(左边的操作对象)不支持该运算时被调用 

rfloordiv(self, other)     当被运算对象(左边的操作对象)不支持该运算时被调用

rmod(self, other)     当被运算对象(左边的操作对象)不支持该运算时被调用

rdivmod(self, other)     当被运算对象(左边的操作对象)不支持该运算时被调用

rpow(self, other)     当被运算对象(左边的操作对象)不支持该运算时被调用

rlshift(self, other)     当被运算对象(左边的操作对象)不支持该运算时被调用

rrshift(self, other)      当被运算对象(左边的操作对象)不支持该运算时被调用

rxor(self, other)     当被运算对象(左边的操作对象)不支持该运算时被调用

ror(self, other)     当被运算对象(左边的操作对象)不支持该运算时被调用

 增量赋值运算

扫描二维码关注公众号,回复: 4688461 查看本文章

iadd(self, other)    定义赋值加法的行为:+=

isub(self, other)    定义赋值减法的行为:-=

imul(self, other)    定义赋值乘法的行为:*=

itruediv(self, other)    定义赋值真除法的行为:/=

ifloordiv(self, other)    定义赋值整数除法的行为://=

imod(self, other)    定义赋值取模算法的行为:%=

ipow(self, other[, modulo])    定义赋值幂运算的行为:**=

ilshift(self, other)    定义赋值按位左移位的行为:<<=

irshift(self, other)    定义赋值按位右移位的行为:>>=

iand(self, other)    定义赋值按位与操作的行为:&=

ixor(self, other)    定义赋值按位异或操作的行为:^=

ior(self, other)    定义赋值按位或操作的行为:|=

 一元操作符


neg(self)    定义正号的行为:+x

pos(self)    定义负号的行为:-x

abs(self)    定义当被 abs() 调用时的行为

invert(self)    定义按位求反的行为:~x

类型转换


complex(self)    定义当被 complex() 调用时的行为(需要返回恰当的值)

int(self)    定义当被 int() 调用时的行为(需要返回恰当的值)

float(self)    定义当被 float() 调用时的行为(需要返回恰当的值)

round(self[, n])    定义当被 round() 调用时的行为(需要返回恰当的值)

index(self)    1. 当对象是被应用在切片表达式中时,实现整形强制转换,2. 如果你定义了一个可能在切片时用到的定制的数值型,你应该定义 index,3. 如果 index 被定义,则 int 也需要被定义,且返回相同的值

上下文管理(with 语句)
     


def __enter__(self): # 1. 定义当使用 with 语句时的初始化行为,2. enter 的返回值被 with 语句的目标或者 as 后的名字绑定
def __exit__(self, exc_type, exc_value, traceback):  # 1. 定义当一个代码块被执行或者终止后上下文管理器应该做什么, 2. 一般被用来处理异常,清除工作或者做一些代码块执行完毕之后的日常工作

容器类型(一般用于操作容器类)


def __len__(self):                  # 定义当被 len() 调用时的行为(一般返回容器类的长度)
def __getitem__(self, key):         # 定义获取容器中指定元素的行为,相当于 self[key]
def __setitem__(self, key, value):  # 定义设置容器中指定元素的行为,相当于 self[key] = value
def __delitem__(self, key):         # 定义删除容器中指定元素的行为,相当于 del self[key]
def __iter__(self):                 # 定义当迭代容器中的元素的行为
def __reversed__(self):             # 定义当被 reversed() 调用时的行为
def __contains__(self, item):       # 定义当使用成员测试运算符(in 或 not in)时的行为

来源:https://blog.csdn.net/weixin_43613890/article/details/85089896

猜你喜欢

转载自www.cnblogs.com/thatme/p/10192992.html