魔法方法
魔法方法是指Python内部已经包含的,被双下划线所包围的方法,这些方法在进行特定的操作时会自动被调用。格式:__method__,method指方法名称。
基础魔法方法
- __init__,初始化时被调用。
class Test():
def __init__(self):
print("执行初始化操作")
def fun1(self):
print("执行了fun1")
a = Test()
输出:
执行初始化操作
- __del__,实例对象被删除时被调用。
class Test():
def __init__(self):
print("执行初始化操作")
def __del__(self):
print("执行del操作")
def fun1(self):
print("执行了fun1")
a = Test()
del(a)
输出:
执行初始化操作
执行del操作
- __len__(self) , 定义当被 len() 调用时的行为。
- __str__(self),定义当被 str() 调用时的行为。
- __format__(self, format_spec),定义当被 format() 调用时的行为。
属性相关的方法
- __getattr__(self, name)、__getattribute__(self, name)、__setattr__(self, name, value)、__delattr__(self, name),
定义获取不存在的属性、获取属性、设置属性、删除属性的行为。 - __dir__(self)、__get__(self, instance, owner)、__set__(self, instance, value)、__delete__(self, instance),定义dir() 被调用、描述符的值被取得、描述符的值被设置、描述符的值被删除的行为。
比较操作符
__lt__(self, other):<
__le__(self, other):<=
__eq__(self, other):=
__ne__(self, other):!=
__gt__(self, other):>
__ge__(self, other):>=
算数运算符
__add__(self, other) :定义加法的行为:+
__sub__(self, other) :定义减法的行为:-
__mul__(self, other) :定义乘法的行为:*
__truediv__(self, other) :定义真除法的行为:/
__floordiv__(self, other) :定义整数除法的行为://
__mod__(self, other) :定义取模算法的行为:%