Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are functions first class objects in python?

I am learning a tutorial on python.It is explaining how functions are first class objects in Python.

def foo():
        pass
print(foo.__class__)

print(issubclass(foo.__class__,object))

The output that I get for the above code is

<type 'function'>
True

This program is supposed to demonstrate that functions are first class objects in python? My questions are as follows.

  1. How does the above code prove that functions are fist class objects?
  2. What are the attributes of a first class object?
  3. what does function.__class__ signify? It returns a tuple <type,function> which doesn't mean much?
like image 792
liv2hak Avatar asked Nov 28 '22 15:11

liv2hak


2 Answers

Here's what Guido says about first class objects in his blog:

One of my goals for Python was to make it so that all objects were "first class." By this, I meant that I wanted all objects that could be named in the language (e.g., integers, strings, functions, classes, modules, methods, etc.) to have equal status. That is, they can be assigned to variables, placed in lists, stored in dictionaries, passed as arguments, and so forth.

The whole blog post is worth reading.

In the example you posted, the tutorial may be making the point that first class objects are generally descendents of the "object" class.

like image 147
Tom Barron Avatar answered Dec 05 '22 14:12

Tom Barron


First-class simply means that functions can be treated as a value -- that is you can assign them to variables, return them from functions, as well as pass them in as a parameter. That is you can do code like:

>>> def say_hi():
        print "hi"
>>> def say_bye():
        print "bye"
>>> f = say_hi
>>> f()
hi
>>> f = say_bye
>>> f()
bye

This is useful as you can now assign functions to variables like any ordinary variable:

>>> for f in (say_hi, say_bye):
        f()
hi
bye

Or write higher order functions (that take functions as parameters):

>>> def call_func_n_times(f, n):
        for i in range(n):
            f()
>>> call_func_n_times(say_hi, 3)
hi
hi
hi
>>> call_func_n_times(say_bye, 2)
bye
bye

About __class__ in python tells what type of object you have. E.g., if you define an list object in python: a = [1,2,3], then a.__class__ will be <type 'list'>. If you have a datetime (from datetime import datetime and then d = datetime.now(), then the type of d instance will be <type 'datetime.datetime'>. They were just showing that in python a function is not a brand new concept. It's just an ordinary object of <type 'function'>.

like image 33
dr jimbob Avatar answered Dec 05 '22 14:12

dr jimbob