title: dynamic adding function to class and make it as bound method
body: <p>I am new in python. I want to write an add_function method for this class to add any function to my class dynamically. This function can manipulate some attributes of my class but it is written outside the class. Assume this class and its method.</p>
  <pre><code>import numpy as np
  import feature_function as ffun
  
  
  
  class Features:
      
      def __init__(self,x,fs=None):
          self.x = x
          self.fs = fs
  
          self.label = []
          self.features = []
  
      def __mean(self, nan_omit = False, min_samples = 1):
          out = ffun.mean(self.x, nan_omit = nan_omit, min_samples = min_samples)
          self.label.extend(['mean'])
          self.features = np.append(self.features,out)
  
  </code></pre>
  <p>now I want to write this function outside of the scope of class:</p>
  <pre><code>def __max(self, nan_omit = False, min_samples = 1):
      out = ffun.max(self.x, nan_omit = nan_omit, min_samples = min_samples)
      self.label.extend(['max'])
      self.features = np.append(self.features,out)
  </code></pre>
  <p>and add it to class. In order to add function to class I have an add_function method inside my class that its arguments are the function that is passed outside the class and also the name of the function.</p>
  <pre><code>
      # Add function dynamically by user
      def add_function(self, name, methodToRun, type ):
          name2 = '__' + name
          # setattr(self, name2, methodToRun)
          setattr(self, mangle_attr(self, name2), methodToRun)
  
  </code></pre>
  <p><code>mangle_attr</code> is a function in order to set private function to a class.</p>
  <pre><code>def mangle_attr(source, attr):
      # if source is an object, get the class
      if not hasattr(source, &quot;__bases__&quot;):
          source = source.__class__
      # mangle attr
      tmp = {}
      code = _mangle_template.format(cls=source.__name__, attr=attr)
      eval(compile(code, '', 'exec'), {}, tmp); 
      return tmp['cls'].mangle.__code__.co_varnames[0]
  
  </code></pre>
  <p>using <code>setattr</code> doesn't bound <code>__max</code> function to my class, for example <code>__mean</code> is bounded in my class, if I call the function I can see:</p>
  <p><code>&lt;bound method Features.__mean of &lt;__main__.Features object at 0x7fd4c91aac10&gt;&gt;</code></p>
  <p>however for <code>__max</code> I still see this:
  <code>&lt;function skewness at 0x7fd2b9dbfb90&gt;</code></p>
  <p>do I have a solution for this problem?</p>