Yes and no. Obviously, they can have attributes assigned to them that work similarly to methods. In addition, the functions come with methods already installed, for example, the __call__ method, which is called using the function.
However, to add a method to an object, what would you usually do? Subclass the class of the object and add a method. However, if you try to subclass a function
imports types class F(types.FunctionType): pass
you will get this error
type 'function' is not an acceptable base type
If you want to create a βcallableβ object that can have methods and use inheritance, try something like this.
class MyCallable(object): def __init__(self): self.message = "Look ma, I got called!" def __call__(self, *args, **kwargs): self.print_message() def print_message(self): print(self.message) class CallableChild(object): def __call__(self, *args, **kwargs): super(CallableChild, self).__call__(*args, **kwargs) print "...as a child, too!"
source share