In the following article, let’s learn about what is a custom class in python. Learn what python custom classes are, and what role python custom classes can play in python programming.
When you see variable or function names in the form of __xxx__ like __slots__, you should pay attention. These have special uses in Python.
__slots__We already know how to use it, and we also know the __len__() method to allow class to act on the len() function.
In addition, there are many special-purpose functions in Python classes that can help us customize classes.
__str__
We first define a Student class and print an instance:
1 2 3 4 5 6 |
|
Print out a bunch of <__main__.Student object at 0x109afb190>, which looks quite ugly.
How can I print it beautifully? You only need to define the __str__() method and return a good-looking string:
1 2 3 4 5 6 7 8 |
|
The instance printed out in this way not only looks good, but also makes it easy to see the important data inside the instance.
But careful friends will find that directly typing the variable without printing, the printed example still does not look good:
1 2 |
|
This is because the direct display of the variable call is not __str__(), but _ _repr__(), the difference between the two is that __str__() returns the string seen by the user, while __repr__() returns the string seen by the program developer. In other words, __repr__() is for debugging.
The solution is to define another __repr__(). But usually the codes of __str__() and __repr__() are the same, so there is a lazy way of writing:
1 2 3 4 5 6 |
|
The above is all the content described in this article, this article mainly introducesPython custom class__str__ related knowledge, I hope you can use the information to understand the above content. I hope what I have described in this article will be helpful to you and make it easier for you to learn python.
For more related knowledge, please visit the Python tutorial column on the php Chinese website.
The above is the detailed content of Python custom class __str__ (detailed examples). For more information, please follow other related articles on the PHP Chinese website!