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
B.method = lambda o: A.method(o,A())
b = B()
b.method()
the line b.method()
then calls A.method(b,A())
. This means a A is initialized each time. To avoid this:
a = A()
B.method = lambda o: A.method(o,a)
now every time you call b.method() on any instance of B the same instance of A is passed as the second argument.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With