Dear python 3 experts,
with python2, one could do the following (I know this is a bit hairy, but that's not the point here :p):
class A(object):
def method(self, other):
print self, other
class B(object): pass
B.method = types.MethodType(A().method, None, B)
B.method() # print both A and B instances
with python3, there is no more unbound methods, only functions. If I want the same behaviour, it sounds like I've to introduce a custom descriptor such as:
class UnboundMethod:
"""unbound method wrapper necessary for python3 where we can't turn
arbitrary object into a method (no more unbound method and only function
are turned automatically to method when accessed through an instance)
"""
def __init__(self, callable):
self.callable = callable
def __get__(self, instance, objtype):
if instance is None:
return self.callable
return types.MethodType(self.callable, instance)
so I can do :
B.method = UnboundMethodType(A().method)
B.method() # print both A and B instances
Is there any other way to do that without writing such descriptor ?
TIA