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..
3 Antwoorden
+ 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.
+ 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.
+ 1
Manav Roy , when you use print() on an object in Python, the interpreter tries to convert that object into a string. More specifically, it first looks for the __str__ method in the object’s class.
If __str__ is not defined, it falls back to __repr__. Here, you haven't defined that, So the code uses the default implementation inherited from the base object class which tells you the class (Vector), module (__main__) and memory address (object at....). This isn’t meant for human readability, but rather as a fallback so you know something exists there.
In Python, objects don’t automatically know how to represent themselves as strings. Unless you explicitly define __str__ or __repr__, Python just shows you its internal pointer i.e.,memory location.
On a side note:
A common pythonic idiom is:-
def __str__(self):
return self.__repr__()