I need to write a class that allows a subclass to set an attribute with the name of a function. Then this function should be called from class instances.
For example, I say that I need to write the Fruit class, where a subclass can convey a greeting message. The Fruit class must set the print_callback attribute, which can be set.
class Fruit(object): print_callback = None def __init__(self, *args, **kwargs): super(Fruit, self).__init__(*args, **kwargs) self.print_callback("Message from Fruit: ")
I need to expose an API that can be used by this code (to be clear, this code cannot change, say, this is third-party code):
def apple_print(f): print "%sI am an Apple!" % f class Apple(Fruit): print_callback = apple_print
If I run:
mac = Apple()
I want to receive:
Posted by Fruit: I'm Apple!
Instead, I get:
TypeError: apple_print () takes exactly 1 argument (2 data)
I think this is because self is passed as the first argument.
So how do I write the Fruit class? Thanks!
python callback
Charles Dietrich
source share