Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

It seems that Python has some limitations regarding instance methods.

  1. Instance methods can't be copied.
  2. 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
938 views
Welcome To Ask or Share your Answers For Others

1 Answer

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...