Which is more fundamental between Python functions and Python object-methods?

PythonServer Side ProgrammingProgramming

A function is a callable object in Python, i.e. can be called using the call operator. However other objects can also emulate a function by implementing __call__method.  

example

def a(): pass # a() is an example of function
print a
print type(a)

Output

C:/Users/TutorialsPoint/~.py
<function a at 0x0000000005765C18>
<type 'function'>

A method is a special class of function, one that can be bound or unbound.

Example

class C:
      def c(self): pass
print C.c   # example of unbound method
print type(C.c)
print C().c  # example of bound method
print type(C().c)
print C.c()

Of course, an unbound method cannot be called without passing as argument.

Output

<function a at 0xb741b5a4>
<type 'function'>
<unbound method C.c>
<type 'instancemethod'>
<bound method C.c of <__main__.C instance at 0xb71ade0c>>
<type 'instancemethod'>
Traceback (most recent call last):
  File "~.py", line 11, in <module>
    print C.c()
TypeError: unbound method c() must be called with C instance as first argument (got nothing instead)

In Python, there is not much difference between a bound method, a function or a callable object (that is an object that implements __call__ method), or a class constructor. They all look the same, they just have different naming conventions and may look vastly different though under the hood.

This means that a bound method can be used as a function, this is one of the many small things that makes Python so powerful

>>> d = A().a #this is a bound method of A()
>>> d() # this is a function

It also means that even though there is a fundamental difference between len(...) and str(...) (str is a type constructor), we won't notice the difference until we go a little deeper:

>>>len
<built-in function len>
>>> str
<type 'str'>
raja
Published on 07-Dec-2017 13:07:14
Advertisements