Given two non-related classes A and B, how to call A.method with an object of B as self?
class A:
def __init__(self, x):
self.x = x
def print_x(self):
print self.x
class B:
def __init__(self, x):
self.x = x
a = A('spam')
b = B('eggs')
a.print_x() #<-- spam
<magic>(A.print_x, b) #<-- 'eggs'
In Python 3.x you can simply do what you want:
If you only have an instance of ‘A’, then get the class first:
In Python 2.x (which the OP uses) this doesn’t work, as noted by the OP and explained by Amber in the comments:
More details (OP edit)
In python 2,
A.print_xreturns an “unbound method”, which cannot be directly applied to other classes’ objects:To work around this restriction, we first have to obtain a “raw” function from a method, via
im_funcor__func__(2.6+), which then can be called passing an object. This works on both classes and instances:In python 3 there’s no such thing anymore as unbound method.
Hence, in python 3,
A.print_xis just a function, and can be called right away anda.print_xstill has to be unbounded: