0

__str__ in Python...

https://sololearn.com/compiler-playground/cdObdQcqZa6s/?ref=app Not sure how does it work. When i remove that method. It prints memory address. Why so? Please explain..

23rd Aug 2025, 3:03 PM
Manav Roy
Manav Roy - avatar
2 Risposte
+ 3
The __str__ method in Python is used to define how an object should be represented as a string. When you remove it, Python's default behavior is to provide a string representation that includes the object's type and its memory address.
23rd Aug 2025, 4:26 PM
BroFar
BroFar - avatar
+ 3
it's the default behavior. if __str__ is not defined, Python will try print the __repr__ method. if that, too is not defined, it will print the default __repr__ defined in the base object class, which is the class name and its memory address enclosed in <>. repr is in lines 492 to 537, but specifically lines 506 to 508 if (Py_TYPE(v)->tp_repr == NULL) return PyUnicode_FromFormat("<%s object at %p>", v->ob_type->tp_name, v); https://github.com/python/cpython/blob/3.6/Objects%2Fobject.c#L506-L508 try to define a __repr__ method to experiment... then see what happens if there is or there's not a __str__ method.
23rd Aug 2025, 4:31 PM
Bob_Li
Bob_Li - avatar