4

I was under the impression that something like str(5) is calling the str function on the integer 5. But when you type str into the interpreter:

>>> str
<class 'str'>

So str is actually a class, which makes code like if type(a) is str make more sense. But then why is str listed under "Built-in Functions" in the docs? Is this just a simplification?

Eli Rose
  • 6,788
  • 8
  • 35
  • 55

3 Answers3

10

Listing it as a function is a bit of a simplification, yes. But remember that classes are callable* — that's how you create an instance of a class!

If it helps you any, think of str(5) as constructing a string from the number 5.

Note that all of the other built-in types exist the same way: int(), float(), str(), tuple(), list(), set(), file()... they're all classes, but they can be called to construct an instance of their class, and will usually accept an instance of another type as an argument if it's applicable.

*: At least, most of the time.

  • Which class is not callable? – Bach Apr 17 '14 at 06:28
  • [An abstract class.](http://stackoverflow.com/q/13646245/149341) Since you can't have an instance of the abstract class itself, it's not callable. (Well, you can call it, but it will always raise an exception.) –  Apr 17 '14 at 07:06
  • Thanks for the reply. So still, you can safely say that every class is callable, or at least - every class has a `__call__` method. – Bach Apr 17 '14 at 07:10
  • Yes. All classes are callable; some just don't do anything useful when you call them. –  Apr 17 '14 at 08:32
1

str(5) is actually calling the __call__() function on the str class:

>>> str(5)
'5'
>>> str.__call__(5)
'5'

So yes, str is behaving as a function as well as a class (or a type in versions prior to 2.7)

dwurf
  • 12,393
  • 6
  • 30
  • 42
  • 2
    Note that this is how **all** function calls work. Every function has a `__call__` method on it. (Including the `__call__` function itself; it's turtles all the way down!) –  Apr 17 '14 at 01:56
0

I think the easy way to look at it is that str() returns an instance of the str class.

clutton
  • 620
  • 1
  • 8
  • 18