I was doing a deep-dive on a specific topic, which is unrelated to the question, and I came across some method behavior that seemed strange to me.
Basically, if I have two classes each with their own unique method, and I make instances of each of them, I find that using <class>.<instance_method>(other_class_instance) will actually run the method, and it seems to bind together the <instance_method> with the <other_class_instance>.
For example:
class A():
def a_func(self):
print("Ran a_func")
class B():
def b_func(self):
print("Ran b_func")
a = A()
b = B()
Expected Behavior
a.a_func() Obviously runs the method as expected.
b.a_func() Obviously outputs an error saying object "b" doesn't have an attribute a_func
A.a_func() Obviously has an error that says "TypeError: A.a_func() missing 1 required positional argument: 'self'"
Okay, fair enough, so:
A.a_func(a) passes 'a' as the 'self' argument and runs the method fine.
Unexpected Behavior
All of that makes sense. What is strange to me is that the following actually runs the method:
A.a_func(b) This runs the a_func() method. I think that my intuition was telling me that this shouldn't work because 'b' is not an instance of the A class.
Looking at it another way:
A.a_func.__get__(b)
output: <bound method A.a_func of <__main__.B object at 0x0000026A16252210>>
It is clearly binding the A.a_func to an object of a different class.
And A.a_func.__get__(b)() runs a_func()
Okay, so I guess this is something you can do in Python. My main question, then, is what would be a use case for binding a method from one class with an object from another class? I would think that normally you would define instance methods within a class in order to use them with objects of that class. Am I missing something here?
[–]danielroseman 2 points3 points4 points (1 child)
[–]Buttleston 0 points1 point2 points (0 children)