问题描述
似乎Python对实例方法有一些限制。
- 无法复制实例方法。
- 实例方法不能被腌制。
这对我来说有问题,面向对象的,其中我引用了实例方法,并且同时使用了deepcopying和pickling。酸洗的东西主要是通过多处理机制完成的。
什么是一个好的方法来解决这个问题?我对复制问题做了一些丑陋的解决方法,但
我正在寻找一个更好的解决这两个问题。
有没有任何建议? p>
更新:
我的用例:我有一个小型事件系统。每个事件都有一个
.action
属性指向它应该触发的函数,有时该函数是某个对象的实例方法。您可以使用。在Python 2.6中:
import copy_reg
import types
def reduce_method
return(getattr,(m .__ self__,m .__ func __.__ name__))
copy_reg.pickle(types.MethodType,reduce_method)
这不会存储方法的代码,只是它的名称;但这将在正常情况下正常工作。
这使得酸洗和复制工作!
It seems that Python has some limitations regarding instance methods.
- Instance methods can't be copied.
- Instance methods can't be pickled.
This is problematic for me, because I work on a very object-oriented project in which I reference instance methods, and there's use of both deepcopying and pickling. The pickling thing is done mostly by the multiprocessing mechanism.
What would be a good way to solve this? I did some ugly workaround to the copying issue, butI'm looking for a nicer solution to both problems.
Does anyone have any suggestions?
Update:
My use case: I have a tiny event system. Each event has an .action
attribute that points to a function it's supposed to trigger, and sometimes that function is an instance method of some object.
You might be able to do this using copy_reg.pickle
. In Python 2.6:
import copy_reg
import types
def reduce_method(m):
return (getattr, (m.__self__, m.__func__.__name__))
copy_reg.pickle(types.MethodType, reduce_method)
This does not store the code of the method, just its name; but that will work correctly in the common case.
This makes both pickling and copying work!
这篇关于克服Python对实例方法的限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!