title: adding a method to a python class while preserving picklability
body: <p>I have an instance of a very complex class A and I wish to add a function to it and be able to pickle it.  I've tried two approaches, neither of which work.  The first is to go for class inheritence, which doesn't seem to copy everything I want:</p>
  
  <pre><code>import pickle, StringIO
  
  class A:
      def __init__(self):
          self.i=1
  
  class B(A):
      def __init__(self, a):
          self = a
  
      def printi(self):
          print self.i
  
  a = A()
  b = B(a)
  
  out = StringIO.StringIO()
  pickle.dump(b,out)
  b.printi() # error, cannot find i
  </code></pre>
  
  <p>The other strategy is to directly add the new function to the instance.  But this will not pickle.</p>
  
  <pre><code>import types, pickle, StringIO
  
  a = A()
  
  def printi(self):
      print self.i
  
  a.printi = types.MethodType(printi, a)
  a.printi()
  out = StringIO.StringIO()
  pickle.dump(a,out) # will not pickle
  </code></pre>
  
  <p>Does anyone know of a way to add a method to the class and keep it picklable at the same time?</p>