I know how to cast to a string, but how does casting to a string actually work? Like if I were to write my own function in python to replace the current str() function how would I do that?
I know how to cast to a string, but how does casting to a string actually work? Like if I were to write my own function in python to replace the current str() function how would I do that?
str as a typeYou cannot replace the str type. It is a base type which cannot be mimicked with a Python class without using str itself.
In the same way, you could not write an int class without using int as it is your builtin way to represent cardinal values.
This happens because Python is a high-level language. You can think of it as an API for using a lot of well-crafted C functions, in the case of CPython. This means you do not have access to key components such as pointers, bit manipulation and memory allocation that would allow you to reimplement some types such as int, str or tuple without somehow using them in the process.
str castAt a more basic level, if what you want is to know how the piping for casting to a string works, it is relatively straightforward.
The function str will call the __str__ method of the object to cast. If it does not exist, it falls back on repr.
def str(obj=''):
if hasattr(obj, '__str__'):
return obj.__str__()
else:
return repr(obj)
It is the responsibility of the object to format a str to be returned by its __str__ method.
You could use the dunder method __str__ to override that of object, and return an intelligible message.
class Example:
def __init__(self, example='an example'):
self.example = example
def __str__(self):
return f'here is the str representation of {self.example}'
example:
e = Example()
print(e) # equivalent to calling print(str(e))
outputs:
here is the str representation of an example
Without the __str__ method, it would revert to using the object one, and the output would be something like this:
<__main__.Example object at 0x10f8da4a8>
Here is a link to the Python Data Model __str__ part
and a link to the python documentation about str objects
where you will find additional background information.