class A(object):
def fun(self):
pass
ins_a = A.fun
ins_b = A().fun
I came across this piece of code and I am unable to understand the difference between the 2 objects.
class A(object):
def fun(self):
pass
ins_a = A.fun
ins_b = A().fun
I came across this piece of code and I am unable to understand the difference between the 2 objects.
Just try the above code in the interactive interpreter:
>>> class A(object):
... def fun(self):
... pass
...
>>> ins_a = A.fun
>>> ins_b = A().fun
>>> ins_a
<unbound method A.fun>
>>> ins_b
<bound method A.fun of <__main__.A object at 0x7f694866a6d0>>
As you can see, it is a matter of bound/unbound methods. A bound method is a method "tied" to an object. You can have a more thorough explanation in this SO answer.
The biggest difference is if you try to call the methods:
If we add a print "hello world"
, it will make it more obvious.
class A(object):
def fun(self):
print ("hello world")
ins_a = A.fun
ins_b = A().fun
Now try calling both:
In [10]: ins_a()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-52906495cc43> in <module>()
----> 1 ins_a()
TypeError: unbound method fun() must be called with A instance as first argument (got nothing instead)
In [11]: ins_b()
hello world
In python 3 they are different types as the unbound method type is gone:
In [2]: type(ins_a)
Out[2]: builtins.function
In [3]: type(ins_b)
Out[3]: builtins.method