Python 魔术方法备忘

魔术方法 调用方式 解释
new(cls [,...]) instance = MyClass(arg1, arg2) new 在创建实例的时候被调用
init(self [,...]) instance = MyClass(arg1, arg2) init 在创建实例的时候被调用
cmp(self, other) self == other, self > other, 等。 在比较的时候调用
pos(self) +self 一元加运算符
neg(self) -self 一元减运算符
invert(self) ~self 取反运算符
index(self) x[self] 对象被作为索引使用的时候
nonzero(self) bool(self) 对象的布尔值
getattr(self, name) self.name # name 不存在 访问一个不存在的属性时
setattr(self, name, val) self.name = val 对一个属性赋值时
delattr(self, name) del self.name 删除一个属性时
__getattribute(self, name) self.name 访问任何属性时
getitem(self, key) self[key] 使用索引访问元素时
setitem(self, key, val) self[key] = val 对某个索引值赋值时
delitem(self, key) del self[key] 删除某个索引值时
iter(self) for x in self 迭代时
contains(self, value) value in self, value not in self 使用 in 操作测试关系时
concat(self, value) self + other 连接两个对象时
call(self [,...]) self(args) “调用”对象时
enter(self) with self as x: with 语句环境管理
exit(self, exc, val, trace) with self as x: with 语句环境管理
getstate(self) pickle.dump(pkl_file, self) 序列化
setstate(self) data = pickle.load(pkl_file) 序列化