猴子补丁 Python 类 [英] Monkey-patch Python class

查看:43
本文介绍了猴子补丁 Python 类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,位于单独的模块中,我无法更改.

I've got a class, located in a separate module, which I can't change.

from module import MyClass

class ReplaceClass(object)
  ...

MyClass = ReplaceClass

除了这个文件之外,这不会改变 MyClass 的任何其他地方.但是,如果我要添加这样的方法

This doesn't change MyClass anywhere else but this file. However if I'll add a method like this

def bar():
   print 123

MyClass.foo = bar

这会起作用,并且 foo 方法将在其他任何地方都可用.

this will work and foo method will be available everywhere else.

如何完全替换类?

推荐答案

import module
class ReplaceClass(object):
    ....
module.MyClass = ReplaceClass

这篇关于猴子补丁 Python 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆