最近在用Mock的mock.patch替换实例方法, 感觉很神奇, 加上之前用过JS, 知道JS中可以为实例方法bind新的实例, 所以猜测在Pyhon这门脚本语言中也应该有类似的机制, 可以让我们修改静态方法(static method), 类方法(class method)和实例方法(intance method). 在SO上搜了一下, 整理一些实验代码, 供大家参考.
[0] - 初始状态
class C(object):
attr = 10
def __init__(self):
self.attr = 20
@classmethod
def cls_m(cls):
print 'cls_m', cls.attr
def ins_m(self):
print 'ins_m', self.attr
@staticmethod