魔术方法
在Python中以两个下划线开头的方法,__init__、__str__、__doc__、__new__等,被称为"魔术方法"(Magic methods)。魔术方法在类或对象的某些事件出发后会自动执行,如果希望根据自己的程序定制自己特殊功能的类,那么就需要对这些方法进行重写。
注意:Python 将所有以 __(两个下划线)开头的类方法保留为魔术方法。所以在定义类方法时,除了上述魔术方法,建议不要以 __ 为前缀。
魔法方法列表
函数名 | 作用 |
---|---|
__init__(self[, ...]) | 构造方法,初始化类的时候被调用 |
__new__(cls[, ...]) | 1. 实例化对象时第一个被调用的方法 2. 其参数直接传递给__init__方法处理 3. 我们一般不会重写该方法 |
__del__(self) | 析构方法,当实例化对象被彻底销毁时被调用 (实例化对象的所有指针都被销毁时被调用) |
__call__(self[, args...]) | 允许一个类的实例像函数一样被调用:x(a, b) 调用 x.call(a, b) |
__str__(self) | 类的字符串表示 |
比较操作符
函数名 | 作用 |
---|---|
__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) |
算数运算符
函数名 | 作用 |
---|---|
__add__(self, other) | 定义加法的行为:+ |
__sub__(self, other) | 定义减法的行为:- |
__mul__(self, other) | 定义乘法的行为:* |
__truediv__(self, other) | 定义真除法的行为:/ |
__floordiv__(self, other) | 定义整数除法的行为:// |
__mod__(self, other) | 定义取模算法的行为:% |
__pow__(self, other[, modulo]) | 定义当被 power() 调用或 ** 运算时的行为 |
示例
class person(object): def __init__(self, num): self.num = num def __lt__(self, other): return self.num < other.num def __pow__(self, other): return self.num ** other.num person1 = person(100) person2 = person(1) print(person1 < person2) print(person1 ** person2)
静态方法
在类中通过装饰器 staticmethod 可以把一个方法变静态方法。
静态方法不会接收隐式的第一个参数,它和普通的函数一样,只是被封装到类中。
通过类和对象都可以调用。
示例:
from types import MethodType class cat(object): def eat(self): print("小猫爱吃鱼") def jiao(self): print("小猫喵喵叫") mao = cat() ''' #动态添加属性 mao.run = "小猫用四条腿跑" print(mao.run) ''' #动态添加方法 def run(self): print("小猫用四条腿跑") mao.pao = MethodType(run, mao) mao.pao() #限制动态添加属性,在class中添加__slots__,然后在后面添加元组即可,然后只能添加元组包括的属性 ''' class cat(object): __slots__ = ("eat", "jiao", "run", "pao") '''