Overcoming Python's limitations regarding instance methods

后端 未结 3 1550
孤城傲影
孤城傲影 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:37

    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!

提交回复
热议问题