Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

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

I have a function defined and object-method as follows

def a(): pass # a() is an example of function
and
class C:
      def c(self): pass
print C().c  # example of bound method

Which is more fundamental between a python function and a python object-method?


1 Answer
Manogna

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.  

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

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'>
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.