Overcoming Python's limitations regarding instance methods

后端 未结 3 1551
孤城傲影
孤城傲影 2020-12-18 00:37

It seems that Python has some limitations regarding instance methods.

  1. Instance methods can\'t be copied.
  2. Instance methods can\'t be pickled.
3条回答
  •  南方客
    南方客 (楼主)
    2020-12-18 01:23

    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()
    

提交回复
热议问题