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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With