Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python2 vs python3 function to method binding

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

like image 968
sthenault Avatar asked Aug 29 '12 11:08

sthenault


1 Answers

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.

like image 54
Sheena Avatar answered Nov 10 '22 06:11

Sheena