title: Writing a class that accepts a callback in Python?
body: <p>I need to write a class that allows a subclass to set an attribute with the name of a function. That function must then be callable from instances of the class.</p>
  
  <p>For example, I say I need to write a Fruit class where the subclass can pass in a welcome message. The Fruit class must expose an attribute print_callback that can be set. </p>
  
  <pre><code>class Fruit(object):
      print_callback = None
  
      def __init__(self, *args, **kwargs):
          super(Fruit, self).__init__(*args, **kwargs)
          self.print_callback("Message from Fruit: ")
  </code></pre>
  
  <p>I need to expose an API that is can be consumed by this code (to be clear, this code cannot change, say it is 3rd party code):</p>
  
  <pre><code>def apple_print(f):
      print "%sI am an Apple!" % f
  
  class Apple(Fruit):
      print_callback = apple_print
  </code></pre>
  
  <p>If I run:</p>
  
  <pre><code>mac = Apple()
  </code></pre>
  
  <p>I want to get:</p>
  
  <blockquote>
    <p>Message from Fruit: I am an Apple!</p>
  </blockquote>
  
  <p>Instead I get:</p>
  
  <blockquote>
    <p>TypeError: apple_print() takes exactly 1 argument (2 given)</p>
  </blockquote>
  
  <p>I think this is because self is passed in as the first argument.</p>
  
  <p>So how do I write the Fruit class? Thanks!</p>