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.
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.
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 is can be consumed by this code (to be clear, this code cannot change, say it is 3rd 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 get:
Message from Fruit: I am an Apple!
Instead I get:
TypeError: apple_print() takes exactly 1 argument (2 given)
I think this is because self is passed in as the first argument.
So how do I write the Fruit class? Thanks!
First define two functions, the callback and the calling code, then pass the callback function into the calling code. The callback function has access to the variables and parameters of the calling function.
A custom callback function can be created by using the callback keyword as the last parameter. It can then be invoked by calling the callback() function at the end of the function. The typeof operator is optionally used to check if the argument passed is actually a function. console.
__call__ in Python The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When the instance is called as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.
Argument() with the keyword argument callback . The function receives the value from the command line. It can do anything with it, and then return the value.
You can use directly:
class Apple(Fruit):
print_callback = staticmethod(apple_print)
or:
class Apple(Fruit):
print_callback = classmethod(apple_print)
In the first case, you'll get only one parameter (the original). In the second, you'll receive two parameters where the first will be the class on which it was called.
Hope this helps, and is shorter and less complex.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With