python_Day09

魔法方法

魔法方法总是被双下划线包围,例如 init
魔法方法的第一个参数应为 cls (类方法) 或者 self (实例方法)。

  1. cls :代表一个类的名称
  2. self :代表一个实例对象的名称

1.基本的魔法方法
init(self[, …])
构造器
new(cls[, …])
析构器
del(self)
strrepr
2.算术运算符
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[, module]) 定义当被 power() 调用或 ** 运算时的行为
lshift(self, other) 定义按位左移位的行为: <<
rshift(self, other) 定义按位右移位的行为: >>
and(self, other) 定义按位与操作的行为: &
xor(self, other) 定义按位异或操作的行为: ^
or(self, other) 定义按位或操作的行为: |
3.反算术运算符
radd(self, other) 定义加法的行为: +
rsub(self, other) 定义减法的行为: -
rmul(self, other) 定义乘法的行为: *
rtruediv(self, other) 定义真除法的行为: /
rfloordiv(self, other) 定义整数除法的行为: //
rmod(self, other) 定义取模算法的行为: %
rdivmod(self, other) 定义当被 divmod() 调用时的行为
rpow(self, other[, module]) 定义当被 power() 调用或 ** 运算时的行为
rlshift(self, other) 定义按位左移位的行为: <<
rrshift(self, other) 定义按位右移位的行为: >>
rand(self, other) 定义按位与操作的行为: &
rxor(self, other) 定义按位异或操作的行为: ^
ror(self, other) 定义按位或操作的行为: |
4.增量赋值运算符
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) 定义赋值按位或操作的行为: |=
5.一元运算符
neg(self) 定义正号的行为: +x
pos(self) 定义负号的行为: -x
abs(self) 定义当被 abs() 调用时的行为
invert(self) 定义按位求反的行为: ~x
6.属性访问
getattrgetattributesetattrdelattr

getattr(self, name) : 定义当用户试图获取一个不存在的属性时的行为。
getattribute(self, name) :定义当该类的属性被访问时的行为(先调用该方法,查看是否存在该属性,若不存 在,接着去调用 getattr )。
setattr(self, name, value) :定义当一个属性被设置时的行为。
delattr(self, name) :定义当一个属性被删除时的行为。

7.描述符
get(self, instance, owner) 用于访问属性,它返回属性的值。
set(self, instance, value) 将在属性分配操作中调用,不返回任何内容。
del(self, instance) 控制删除操作,不返回任何内容。
8.定制序列
容器类型的协议

  1. 如果说你希望定制的容器是不可变的话,你只需要定义 len() 和 getitem() 方法。
  2. 如果你希望定制的容器是可变的话,除了 len() 和 getitem() 方法,你还需要定义 setitem()
    delitem() 两个方法。

len(self) 定义当被 len() 调用时的行为(返回容器中元素的个数)。
getitem(self, key) 定义获取容器中元素的行为,相当于 self[key] 。
setitem(self, key, value) 定义设置容器中指定元素的行为,相当于 self[key] = value 。
delitem(self, key) 定义删除容器中指定元素的行为,相当于 del self[key] 。

9.迭代器
迭代器有两个基本的方法: iter() 和 next()

iter(object) 函数用来生成迭代器。 next(iterator[, default]) 返回迭代器的下一个项目。
iterator – 可迭代对象 default –
可选,用于设置在没有下一个元素时返回该默认值,如果不设置,又没有下一个元素则会触发StopIteration 异常。

把一个类作为一个迭代器使用需要在类中实现两个魔法方法 iter() 与 next()

10.生成器
yield 的函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值