Overcoming Python#39;s limitations regarding instance methods(克服 Python 关于实例方法的限制)
问题描述
似乎 Python 在实例方法方面有一些限制.
It seems that Python has some limitations regarding instance methods.
- 无法复制实例方法.
- 实例方法不能被pickle.
这对我来说是个问题,因为我在一个非常面向对象的项目中工作,我在其中引用了实例方法,并且使用深度复制和酸洗.酸洗的事情主要是由多处理机制来完成的.
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, but I'm looking for a nicer solution to both problems.
有人有什么建议吗?
更新:
我的用例:我有一个很小的事件系统.每个事件都有一个 .action 属性,该属性指向它应该触发的函数,有时该函数是某个对象的实例方法.
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.
推荐答案
您也许可以使用 copy_reg.pickle.在 Python 2.6 中:
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 关于实例方法的限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:克服 Python 关于实例方法的限制
基础教程推荐
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
