rish
rish

Reputation: 101

Is there a difference between str() function and class str in Python

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?

Upvotes: 1

Views: 611

Answers (2)

Karl Knechtel
Karl Knechtel

Reputation: 61643

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

Upvotes: 0

user2390182
user2390182

Reputation: 73498

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.

Upvotes: 1

Related Questions