克服 Python 关于实例方法的限制
Python 在实例方法方面似乎有一些限制。
- 实例方法无法复制。
- 实例方法不能被 pickle。
这对我来说是有问题的,因为我从事一个非常面向对象的项目,其中我引用了实例方法,并且使用了深度复制和酸洗。酸洗工作主要是通过多处理机制完成的。
解决这个问题的好方法是什么?我对复制问题做了一些丑陋的解决方法,但是 我正在寻找解决这两个问题的更好方法。
有人有什么建议吗?
更新:
我的用例:我有一个小型事件系统。每个事件都有一个 .action
属性,该属性指向它应该触发的函数,有时该函数是某个对象的实例方法。
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, but
I'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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
copy_reg.pickle
< 来完成此操作/a>.在 Python 2.6 中:这不存储方法的代码,只存储其名称;但这在常见情况下可以正常工作。
这使得酸洗和复制都可以工作!
You might be able to do this using
copy_reg.pickle
. In Python 2.6: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!
REST - 表示状态转移。只发送状态,不发送方法。
要将对象 X 从 A 传输到 B,我们这样做。
A 在某些情况下对 X 的状态进行编码
方便、易于解析的符号。 JSON
很流行。
A 将 JSON 文本发送给 B。
B 将 X 的状态解码为 JSON
符号,重建X。
必须具有 X 类的类定义才能正常工作。 B 必须具有 X 的类所依赖的所有函数和其他类定义。简而言之,两者都是A
和 B 具有所有定义。仅移动对象状态的表示
大约。
请参阅任何有关 REST 的文章。
http://en.wikipedia.org/wiki/Representational_State_Transfer
http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm
REST - Representation State Transfer. Just send state, not methods.
To transfer an object X from A to B, we do this.
A encode the state of X in some
handy, easy-to-parse notation. JSON
is popular.
A sends the JSON text to B.
B decodes the state of X form JSON
notation, reconstructing X.
B must have the class definitions for X's class for this to work. B must have all functions and other class definitions on which X's class depends. In short, both A
and B have all the definitions. Only a representation of the object's state gets moved
around.
See any article on REST.
http://en.wikipedia.org/wiki/Representational_State_Transfer
http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm
pickle 实例,然后在 unpickle 后访问该方法。 Pickling 实例的方法没有意义,因为它依赖于实例。如果没有,那就写成一个独立的函数。
pickle the instance and then access the method after unpickling it. Pickling a method of an instance doesn't make sense because it relies on the instance. If it doesn't, then write it as an independent function.