1

The Python Language Reference 3.11.1 mentions a str() function as:

Some operations are supported by several object types; in particular, practically all objects can be compared for equality, tested for truth value, and converted to a string (with the repr() function or the slightly different str() function).

How is this different from the class str? Or, when I write

str()

What is called? The function or the class?

rish
  • 101
  • 9
  • This might be of interest [here](https://stackoverflow.com/questions/41168899) – user19077881 Jan 29 '23 at 10:08
  • Thé documentation is very clear, it starts with "class str(object='')". So yes, it's a class, and I guess that it's called the str 'function' in some places in order not to sound overly complicated. After all, it's callable, and most of the time it doesn't make any difference... – Thierry Lathuille Jan 29 '23 at 10:08
  • @ThierryLathuille calling it callable might be irritating because usually that term refers to classes implementing `__call__()` whose *instances* are callable. Classes themselves can always be called, as that is the language's way of instantiating them by invoking their constructor. – user2390182 Jan 29 '23 at 10:17
  • @user2390182 There **isn't anything different** about this case. Classes **are** instances of `type`, which **does** implement `__call__`. Calling the class goes through that `type.__call__` logic first, which redirects to `object.__new__`, which invokes built-in machinery, which **only then** (normally) calls `__init__`. – Karl Knechtel Feb 13 '23 at 13:08

2 Answers2

1

Check the output of help(str):

class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |  
 |  Create a new string object from the given object. [...]
 |  Otherwise, returns the result of object.__str__() (if defined)
 |  or repr(object).

So, in short: str(obj) calls the constructor of the str class. What you refer to as the str function is exactly that: the class' constructor.

user2390182
  • 72,016
  • 6
  • 67
  • 89
0

There is no "str() function`. This part of the documentation is deliberately inaccurate in order to explain things more simply.

In Python, classes are callable, and normally calling them is the way to create an instance of the class. This does more than the __init__ method in the class: it's the part that will interface with Python's behind-the-scenes stuff in order to actually allocate memory for the object, set it up for reference-counting, identify what class it's an instance of, etc. etc.

str is the class of strings. Calling str creates a string. The documentation calls this a "function" because it looks like one. Similarly for other types, such as int and - well - type (the class that classes are instances of (by default), including itself).

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153