Auto-adding Functions to a Python Class

Jun 03, 2009 15:32

Often times you need to write wrappers or proxies that are required to support "forwarding functions", i.e. functions that just forward requests to similarly named functions, or do something parametrised by function name. The tedious way to do it is something like this:

class C ( Read more... )

code-generation, geekdom, python, hacking

Leave a comment

Comments 6

both are different anonymous June 3 2009, 16:35:42 UTC
In first case a,b,c are methods. They get the implicit self parameter when you call. In second case, it's a function on the object. You should create a function accepting two arguments (self, arg) and assign it to class C instead of the instance of C

Reply

Re: both are different code_martial June 4 2009, 03:55:23 UTC
Don't just tell. Show.

Reply

Re: both are different anonymous June 4 2009, 17:21:55 UTC
ok.. hope the below example makes it clear

>>> class Person(object):
... def __init__(self, name):
... self.name = name
...
>>> joe = Person('Joe')
>>> joe.fullName = lambda : None #function on joe object. No way to access self
>>> print joe.fullName()
None
>>> del joe.fullName #Lets delete that function
>>> Person.fullName = lambda self: self.name #Now adding function on Person
>>> print joe.fullName() #This is a bound method to joe. No need to pass self
Joe
>>>

Reply

Re: both are different code_martial June 5 2009, 04:21:47 UTC
Okay, this does it (except, I'm not sure if it's multiple-import proof):

class C:
@staticmethod
def gen_func(name):
return (lambda self, arg: name + arg)

def __init__(self):
pass

fnames = ['a', 'b', 'c']
for fname in fnames:
C.__dict__[fname] = C.gen_func(fname)

################
# Let's try it out
################

if __name__ == '__main__':
a_c = C()
print a_c.a('a')
print a_c.b('b')
print a_c.c('c')

Reply


Leave a comment

Up