What does the print() function do behind the scenes to handle different
data types?
It uses the type() function to determine the data type and handle it accordingly.
It uses a series of if statements to handle each data type individually.
It implicitly calls str() to type cast any object into a string.
It throws an error if the data type isn’t a string.
Please provide any python documentation to support your answer ‘It implicitly calls str() to type cast any object into a string.’
Hi @Govindarajan_Shanmug ,
When print
is called on an instance/object, it should invoke the __str__
method to obtain the string representation of the object.
For Example, Try Executing.
class MyClass:
def __str__(self):
return "This is from __str__ method."
def __repr__(self):
return "This is from __repr__ method."
# Create an instance of MyClass
obj = MyClass()
print(obj)
print(str(obj))
print(repr(obj))
From documentation of cpython: cpython/Python/bltinmodule.c at v3.13.0b4 · python/cpython · GitHub you can try to infer details from this.
Other reference: How To Use the __str__() and __repr__() Methods in Python | DigitalOcean
Hope this would answer your question.