【发布时间】:2014-03-05 15:07:29
【问题描述】:
是否可以对 Python 类中的属性进行猴子修补? “猴子修补 python”的快速谷歌返回大量关于修补 methods 的结果,但没有提及更改类中的字段。
修补方法:
- Adding a Method to an Existing Object
- Duck punching a property
- changing methods and attributes at runtime
但是,就像我说的,没有提到更改类属性/字段。
举一个有点人为的例子,假设我有一个有multiprocessingqueue 的类,我想用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>
有没有办法做到这一点?
【问题讨论】:
-
您必须要么创建原始类的实例,然后重写字段的实际值,要么通过替换构造函数来修改类。但我完全不推荐使用猴子补丁。通常有更好的方法来解决您遇到的问题。
-
猴子补丁首先需要什么?
标签: python