Python Practical Notes (26) Object-Oriented Advanced Programming - Custom Classes

Python's class allows the definition of many custom methods, allowing us to generate specific classes very easily. The following are common customization methods in the concentration:

How can I print beautifully? Just define a __str__()method that returns a nice-looking string:

__str__()

>>> class Student(object): ... def __init__(self, name): ... self.name = name ... def __str__(self): ... return 'Student object (name: %s)' % self.name ... >>> print(Student('Michael')) Student object (name: Michael) 

The instance printed in this way is not only good-looking, but also easy to see the important data inside the instance.

But careful friends will find that there is no need to type variables directly print, and the printed examples are still not good-looking:

>>> s = Student('Michael')
>>> s
<__main__.Student object at 0x109afb310> 

This is because the direct display variable call is not __str__(), but __repr__(), the difference between the two is __str__()to return the string seen by the user, and __repr__()return the string seen by the program developer, that is to say, it __repr__()is for debugging.

The solution is to define another one __repr__(). But it is usually __str__()the __repr__()same as the code, so there is a lazy way of writing:

class Student(object):
    def __init__(self, name): self.name = name def __str__(self): return 'Student object (name=%s)' % self.name __repr__ = __str__ 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326091490&siteId=291194637