Apply A Method To An Object Of Another Class
Solution 1:
In Python 3.x you can simply do what you want:
A.print_x(b) #<-- 'eggs'
If you only have an instance of 'A', then get the class first:
a.__class__.print_x(b) #<-- 'eggs'
In Python 2.x (which the OP uses) this doesn't work, as noted by the OP and explained by Amber in the comments:
This is a difference between Python 2.x and Python 3.x - methods in 3.x don't enforce being passed the same class.
More details (OP edit)
In python 2, A.print_x
returns an "unbound method", which cannot be directly applied to other classes' objects:
When an unbound user-defined method object is called, the underlying function (im_func) is called, with the restriction that the first argument must be an instance of the proper class (im_class) or of a derived class thereof. >> http://docs.python.org/reference/datamodel.html
To work around this restriction, we first have to obtain a "raw" function from a method, via im_func
or __func__
(2.6+), which then can be called passing an object. This works on both classes and instances:
# python 2.5-
A.print_x.im_func(b)
a.print_x.im_func(b)
# python 2.6+
A.print_x.__func__(b)
a.print_x.__func__(b)
In python 3 there's no such thing anymore as unbound method.
Unbound methods are gone for good. ClassObject.method returns an ordinary function object, instance.method still returns a bound method object. >> http://www.python.org/getit/releases/3.0/NEWS.txt
Hence, in python 3, A.print_x
is just a function, and can be called right away and a.print_x
still has to be unbounded:
# python 3.0+
A.print_x(b)
a.print_x.__func__(b)
Solution 2:
You don't (well, it's not that you can't throw enough magic at it to make it work, it's that you just shouldn't). If the function is supposed to work with more than one type, make it... a function.
# behold, the magic and power of duck typing
def fun(obj):
print obj.x
classA:
x = 42classB:
x = 69fun(A())
fun(B())
Solution 3:
I don't know why you would really want to do this, but it is possible:
>>>classA(object):...deffoo(self):...print self.a...>>>classB(object):...def__init__(self):... self.a = "b"...>>>x = A()>>>y = B()>>>x.foo.im_func(y)
b
>>>A.foo.im_func(y)
b
An instance method (a class instance's bound method) has a property called im_func
which refers to the actual function called by the instance method, without the instance/class binding. The class object's version of the method also has this property.
Post a Comment for "Apply A Method To An Object Of Another Class"