title: Python metaprogramming: automatically generate member functions
body: <p>How do I write a function that adds a method to a class?  I have:</p>
  
  <pre><code>class A:
      def method(self):
          def add_member(name):
              self.new_method = def name...?
  
          add_member("f1")
          add_member("f2")
  </code></pre>
  
  <p>In order to answer what I'm trying to do.  I'm trying to factor out some pyqt slots.  I want to be able to call a function <code>create_slider</code> that will create a <code>QSlider</code> and a <code>QLabel</code> and create the slider handling code, and make the slider-handler update the text in the <code>QLabel</code>.  Here's the slot that needs to be factored out:</p>
  
  <pre><code>    def on_sample_slider(self, value):
          self.samples = pow(4, value)
          self.sample_label.setText('%d' % self.samples)
  </code></pre>
  
  <p>here's a method that generates some UI, but it would be nice to also have it generate the on_sample_slider method every time it is called:</p>
  
  <pre><code>    def insert_labeled_slider(hbox, name, slider_target):
          # name
          hbox.addWidget(QLabel(name))
  
          # label
          label = QLabel()
          label.setMinimumSize(40, 0)
          hbox.addWidget(self.sample_label)
  
          #slider
          slider = QSlider(Qt.Horizontal)
          slider.setRange(0, 6)
          slider.setTracking(True)
          slider.setPageStep(1)
          hbox.addWidget(slider)
  
          self.connect(self.sample_slider, SIGNAL('valueChanged(int)'),
                       self.on_sample_slider)
          self.sample_slider.setValue(0)
          return (label, slider)
  </code></pre>
  
  <p>Final code:</p>
  
  <pre><code>def attach_on_slider(obj, name, variable, label, base):
      def on_slider(self, value):
          variable = base**value
          label.setText('%d' % variable)
  
      # This next line creates a method from the function
      # The first arg is the function and the second arg is the object
      # upon which you want it to be a method.
      method = types.MethodType(on_slider, obj)
      obj.__dict__["on_slider_" + name] = method
      return method
  
  class A:
      def insert_labeled_slider(hbox, name, label_name, variable):
          # name
          hbox.addWidget(QLabel(label_name))
  
          # label
          label = QLabel()
          label.setMinimumSize(40, 0)
          hbox.addWidget(label)
  
          #slider
          slider = QSlider(Qt.Horizontal)
          slider.setRange(0, 6)
          slider.setTracking(True)
          slider.setPageStep(1)
          hbox.addWidget(slider)
  
          on_slider_method = attach_on_slider(self, name, variable, label, 4)
  
          self.connect(slider, SIGNAL('valueChanged(int)'),
                       on_slider_method)
          slider.setValue(0)
          return (label, slider)
  </code></pre>