>>> 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!
ReplyDelete