Python's class allows you to define many custom methods that make it very easy to generate specific classes. The following are the common custom methods of centralization:
How can you print it well? Just define a good __str__()
method and return 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)
This kind of printed example, not only good-looking, but also easy to see the important data inside the instance.
But careful friends will find that the direct knocking variable print
is not used, the printed example is not good to see:
>>> s = Student(‘Michael‘)>>> s<__main__.Student object at 0x109afb310>
This is because the direct display of variable calls is not __str__()
, but the __repr__()
difference between the two is to return the string that the __str__()
user sees, and the __repr__()
string that the program developer sees, that __repr__()
is, for debugging services.
The solution is to define one more __repr__()
. But it's usually __str__()
__repr__()
the same as the code, so there's a lazy way to do it:
class Student(object): def __init__(self, name): self.name = name def __str__(self): return ‘Student object (name=%s)‘ % self.name __repr__ = __str__
Python Practical Notes (26) object-oriented advanced programming--Custom classes