Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22871

Python Morsels: Python's "functions" are sometimes classes

$
0
0

Sometimes we call classes functions in Python. Why? And what's a "callable"?

Class or function?

There's a group activity I often do when training new Python developers: the class or function game.

In the class or function game, we take something that we "call" (using parentheses: ()) and we guess whether it's a class or a function.

For example:

  • We can call zip with a couple iterables and we get another iterable back, so is zip a class or a function?
  • When we call len, are we calling a class or a function?
  • What about int: when we write int('4') are we calling a class or a function?

Python's zip, len, and int are all often guessed to be functions, but only one of these is really a function:

>>> zip<class 'zip'>>>> len<built-in function len>>>> int<class 'int'>
>>> zip<class 'zip'>>>> len<built-in function len>>>> int<class 'int'>

While len is a function, zip and int are classes.

The reversed, enumerate, range, and filter"functions" also aren't really functions:

>>> reversed<class 'reversed'>>>> enumerate<class 'enumerate'>>>> range<class 'range'>>>> filter<class 'filter'>
>>> reversed<class 'reversed'>>>> enumerate<class 'enumerate'>>>> range<class 'range'>>>> filter<class 'filter'>

After the class or function game, we often talk discuss:

  • The term "callable" (and how classes are callables)
  • The fact that in Python we often don't care whether something is a class or a function

What's a callable?

A callable is anything you …

Read the full article: https://www.pythonmorsels.com/class-function-and-callable/


Viewing all articles
Browse latest Browse all 22871

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>