paweloque
paweloque

Reputation: 18864

Generic methods in python

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

Upvotes: 10

Views: 14942

Answers (3)

David Webb
David Webb

Reputation: 193716

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.

Upvotes: 16

Andrey Sboev
Andrey Sboev

Reputation: 7682

class FooBar:
    def __getattr__(self, name):
        def foo():
            print name
        return foo

a = FooBar()
a.helloThere()

Upvotes: 4

Karoly Horvath
Karoly Horvath

Reputation: 96266

def __getattr__(self, name):
  #return your function here...

Upvotes: 6

Related Questions