猴子修补类中的属性?

时间:2014-02-08 01:27:55

标签: python

是否有可能在Python类中使用Monkey Patch属性?一个关于“猴子修补python”的快速谷歌返回了大量关于修补methods的结果,但没有提到改变类中的字段。

修补方法:

但是,就像我说的那样,没有提到改变Class属性/字段。

为了给出一个有点人为的例子,假设我有一个有multiprocessing queue的课程,我想用threading Queue.Queue修补它。

import threading 
import multiprocessing

class MyClassWithAQueue(object):
        def__init__(self):
                self.q = multiprocessing.Queue()

有没有办法修补这个?在构造之前尝试通过类名简单地分配它似乎什么都不做。

if __name__ == '__main__':
        MyClassWithAQueue.q = Queue.Queue()
        myclass = MyClassWithAQueue()

        print myclass.q 
            # still shows as a multiprocessing queue
        >>><multiprocessing.queues.Queue object at 0x10064493>

有办法做到这一点吗?

1 个答案:

答案 0 :(得分:1)

问题是代码运行的 order

__init__在实例化时运行,并且正在设置self.q,无论之前是什么。您可以执行以下操作之一:


将其更改为类属性:

class MyClassWithAQueue(object):
    q = multiprocessing.Queue()
    def __init__(self):
        pass

MyClassWithAQueue.q = Queue.Queue()
myclass = MyClassWithAQueue()
print myclass.q

或更改实例属性:

class MyClassWithAQueue(object):
    def __init__(self):
        self.q = multiprocessing.Queue()

myclass = MyClassWithAQueue()
myclass.q = Queue.Queue()
print myclass.q