A Python Trick: Adding a Lambda Method to a Class
It does not take much to add a lambda function to a Python class. For example, consider the following:
This code adds the method f to class A. For example:
However, the f method created this way does not have the expected Python name:
Further, defining this value is not possible; the instancemethod f does not have a __name__ attribute.
The trick is to name the lambda function before defining the class method:
This is simple, but it took too long to figure this out...
>>> class A: pass
>>> f = lambda self,x:x
>>> setattr(A,"f",f)
This code adds the method f to class A. For example:
>>> a=A()
>>> a.f(1)
1
However, the f method created this way does not have the expected Python name:
>>> A.f.__name__
''
Further, defining this value is not possible; the instancemethod f does not have a __name__ attribute.
The trick is to name the lambda function before defining the class method:
>>> class A: pass
>>> f = lambda self,x:x
>>> f.__name__ = "f"
>>> setattr(A,"f",f)
>>> f.__name__
'f'
This is simple, but it took too long to figure this out...
Thanks!
ReplyDeleteSetting an attribute directly might help.
ReplyDeleteA.f=lambda x:x
Here's a more pythonic sample:
ReplyDeleteclass Greeter:
def __init__(self):
# put a lambda here
self.hello = lambda:'Hello World'
my_obj = Greeter()
print my_obj.hello()