python中的monkey-patching

简介: 这个技巧我很少用过。 但知道无防。 在运行时改变函数或类的行为, 一般用猴子补丁,原类,装饰器都可以实现。 #!/usr/bin/env python # -*- coding: utf-8 -*- import types class Class(object): ...

这个技巧我很少用过。

但知道无防。

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

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

#!/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)

目录
相关文章
|
8月前
|
存储 开发工具 开发者
命令行参数解析神器:深入剖析Python中的argparse模块
命令行参数解析神器:深入剖析Python中的argparse模块
|
10月前
|
数据处理 Python
Python中的偏函数(Partial Functions)
Python中的偏函数是来自函数式编程的一个强大工具,它的主要目标是减少函数调用的复杂性。这个概念可能起初看起来有点困难理解,但一旦你明白了它的工作方式,它可能会成为你的编程工具箱中的重要组成部分。
|
容器 Docker
解决Unable to locate package python3-pip3
解决Unable to locate package python3-pip3
159 0
|
Python
python中关于 name 'self' is not defined这种错误解决方法
python中关于 name 'self' is not defined这种错误解决方法
82 0
python中关于 name 'self' is not defined这种错误解决方法
|
Python
RuntimeError: Python is not installed as a framework
RuntimeError: Python is not installed as a framework
|
Linux Python
Python - os.walk()详细使用
Python - os.walk()详细使用
184 0
|
Unix API Python
每周一个 Python 模块 | pathlib
使用面向对象的 API 而不是低级字符串操作来解析,构建,测试和以其他方式处理文件名和路径。
111 0