且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

python中的monkey-patching

更新时间:2022-08-16 17:20:49

这个技巧我很少用过。

但知道无防。

在运行时改变函数或类的行为,

一般用猴子补丁,原类,装饰器都可以实现。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import types

class Class(object):
    def add(self, x, y):
        return x + y

inst = Class()
def not_exactly_add(self, x, y):
    return x * y

print inst.add(3, 4)

Class.add = not_exactly_add

print inst.add(3, 4)

class TClass(object):
    def add(self, x, y):
        return x + y
    def become_more_powerful(self):
        old_add = self.add
        def more_powerful_add(self, x, y):
            return old_add(x, y) + 1
        self.add = types.MethodType(more_powerful_add, self)

inst = TClass()
inst.old_add = inst.add
print  inst.add(3, 4)
inst.become_more_powerful()
print  inst.add(3, 4)
inst.become_more_powerful()
inst.become_more_powerful()
inst.become_more_powerful()
print  inst.add(3, 4)
print  inst.old_add(3, 4)

python中的monkey-patching