1
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.

user1251007
  • 15,891
  • 14
  • 50
  • 76
sam
  • 635
  • 4
  • 9
  • 18
  • 1
    `()` makes an instance and calls `fun` on it, the other calls it directly on the class – Tim Jun 13 '14 at 12:07
  • possible duplicate of [Class method differences in Python: bound, unbound and static](http://stackoverflow.com/questions/114214/class-method-differences-in-python-bound-unbound-and-static) – K DawG Jun 13 '14 at 12:15

2 Answers2

2

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.

Community
  • 1
  • 1
linkyndy
  • 17,038
  • 20
  • 114
  • 194
  • 3
    Perhaps it's good to explain the difference between bound and unbound – Tim Jun 13 '14 at 12:09
  • Was just trying to find a perfect explanation for this topic as you were posting the comment. Hope it will help the OP :) – linkyndy Jun 13 '14 at 12:11
1

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
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321