Electron microscopy
 
PythonML
__str__ method for a class
- Python Automation and Machine Learning for ICs -
- An Online Book -
Python Automation and Machine Learning for ICs                                                           http://www.globalsino.com/ICs/        


Chapter/Index: Introduction | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z | Appendix

=================================================================================

In Python, the __str__ method is a special method used to define the string representation of an object. When you call the built-in str() function or use print() with an object instance, Python internally calls the __str__ method of that object to obtain the string representation, for instance (Code): 

 

   Output: 

 

In this example, the __str__ method is defined within the MyClass class. It returns a string that represents the object in a meaningful way. When str(obj) or print(obj) is called, Python internally invokes the __str__ method of the obj instance, which returns the specified string representation. Implementing a __str__ method is helpful for providing a human-readable representation of objects, making it easier to understand their state and contents during debugging and development. 

The code below doesn't have a custom __str__ method defined within the MyClass class.

Therefore, when we print the object obj, Python resorts to the default string representation, which includes the class name and the memory address where the object is located in memory:  

When we print an object without a custom __str__ method, Python uses the default string representation, which is essentially <class_name object at memory_address>. In this case, MyClass is the class name, and 0x104b90d10 is the memory address where the obj instance is stored in memory. 

============================================

         
         
         
         
         
         
         
         
         
         
         
         
         
         
         
         
         
         

 

 

 

 

 



















































 

 

 

 

 

=================================================================================