Overcoming Python's limitations regarding instance methods

时光总嘲笑我的痴心妄想 提交于 2019-11-29 06:53:34

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!

REST - Representation State Transfer. Just send state, not methods.

To transfer an object X from A to B, we do this.

  1. A encode the state of X in some handy, easy-to-parse notation. JSON is popular.

  2. A sends the JSON text to B.

  3. 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 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.

import pickle

class A:
     def f(self):
         print 'hi'

x = A()
f = open('tmp', 'w')
r = pickle.dump(x, f)
f.close()
f = open('tmp', 'r')
pickled_x = pickle.load(f)
pickled_x.f()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!