__str__ trong python
In Python __str__ is meant to return the object’s human-friendly representation, while __repr__ should return a valid python expression that can be used to recreate the object. Show In the following sections, we’ll look at some examples, and I’ll show you how to implement these magic methods correctly for your own classes. Table of Contents Magic MethodsMost of the “automagical” behavior - like comparision, conversion or object initialization - of Python classes are implemented as magic methods or the so-called dunder methods. The name comes from the double underscore naming conventions. These methods are usually not called explicitly, but get triggered automatically in certain scenarios. str() and repr() vs str() and repr()A good example can be the Both return a kind of string representation of the given object, with a slight, but important difference between the two. What’s The Goal of str()?
What Is repr() For?In contrast In other words If this is not possible, then Default ImplementationsIf a class does not implement a custom For this reason it is always a good idea to implement a working, meaningful Containers And Recursive Data StructuresIt might be surprising at first, so it’s good to note here that all containers’ and recursive data structures’ Summary: in this tutorial, you’ll learn how to use the Python Introduction to the Python __str__ methodLet’s start with the
The 0, 1, and 2. The following creates a new instance of the
Output:
When you use the 4 function to display the instance of the Person class, the 4 function shows the memory address of that instance. Sometimes, it’s useful to have a string representation of an instance of a class. To customize the string representation of a class instance, the class needs to implement the Internally, Python will call the 9 method. Note that the 4 function converts all non-keyword arguments to strings by passing them to the 9 before displaying the string values. The following illustrates how to implement the
And when you use the 4 function to print out an instance of the Person class, Python calls the __str__ method defined in the Person class. For example: |