Is it possible to implement generic method handlers in python which allow for calling of non-existent functions? Something like this:
class FooBar:
def __generic__method__handler__(.., methodName, ..):
print methodName
fb = FooBar()
fb.helloThere()
-- output --
helloThere
A generic function is composed of multiple functions implementing the same operation for different types. Which implementation should be used during a call is determined by the dispatch algorithm. When the implementation is chosen based on the type of a single argument, this is known as single dispatch.
Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.
Python has always provided a variety of built-in and standard-library generic functions, such as len() , iter() , pprint. pprint() , copy. copy() , and most of the functions in the operator module.
The print() function is an example of a generic function. A generic function is simply a function that performs a common task by dispatching its input to a particular method-function that is selected on the basis of the class of the input to the generic function.
The first thing to remember is that methods are attributes which happen to be callable.
>>> s = " hello "
>>> s.strip()
'hello'
>>> s.strip
<built-in method strip of str object at 0x000000000223B9E0>
So you can handle non-existent methods in the same way you would handle non-existent attributes.
This is usally done by defining a __getattr__
method.
Now you're going hit the additional complexity which is the difference between functions and method. Methods need to be bound to an object. You can take a look at this question for a discussion of this.
So I think you'll want something like this:
import types
class SomeClass(object):
def __init__(self,label):
self.label = label
def __str__(self):
return self.label
def __getattr__(self, name):
# If name begins with f create a method
if name.startswith('f'):
def myfunc(self):
return "method " + name + " on SomeClass instance " + str(self)
meth = types.MethodType(myfunc, self, SomeClass)
return meth
else:
raise AttributeError()
Which gives:
>>> s = SomeClass("mytest")
>>> s.f2()
'method f2 on SomeClass instance mytest'
>>> s.f2
<bound method SomeClass.myfunc of <__main__.SomeClass object at 0x000000000233EC18>>
However, I'd probably recommend against using this. If you tell us the problem you're trying to solve I expect someone here can come up with a better solution.
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