- 1. Preface
- 2. Str& The repr method
- 2.1. Rewrite the str method
- 2.2 Rewrite__Repr__
- 2.3 Rewriting__Str__& Amp__Repr__method
- 3. Summary
- Reference
1. Preface
class People:
def __init__(self,name,sex):
self.name = name
self.sex = sex
p = People('xiaoming','male')
'''
In:p
OutPut:<__main__.People at 0x7fddfeif>
In:print(p)
OutPut:<__main__.People at 0x7fddfeif>
'''
- The information displayed in both ways is the name of the class to which the object belongs and the address where the object is located.
- By rewriting__Str__And__Repr__Method to customize the information we want.
2. Str& The repr method
Str And Repr Method is a string description of a custom class, and when we print or view an object, the final result we see is the return value of these two methods.
2.1. Rewrite the str method
class A:
def __str__(self):
return '__str__'
a = A()
'''
In:a
OutPut:<__main__.People at 0x7fddfeif>
In:print(a)
OutPut:__str__
'''
Directly input the object and press enter to return the same result as before; But when printing the printed object, it triggered__Str__Method.
2.2 Rewrite__Repr__
class B:
def __repr__(self):
return '__repr__'
b = B()
'''
In:b
OutPut:__repr__
In:print(b)
OutPut:__repr__
'''
Directly inputting b and printing through print are both calls__Repr__Method.
2.3 Rewriting__Str__& Amp__Repr__Method
class C:
def __str__(self):
return '__str__'
def __repr__(self):
return '__repr__'
c = C()
'''
In:c
OutPut:__repr__
In:print(c)
OutPut:__str__
'''
- In interactive mode, directly inputting object c calls the__Repr__method
- When printing objects, call directly if there are any__Str__Method, then call directly__Str__Method, if not available, call__Repr__Method, if neither method is present, the memory address information of the class will be printed normally.
3. Summary
- __Str__It is an informal and easy to read string description of an object that is called when the class str is instantiated (str (object)), as well as by the built-in functions format() and print();
- __Repr__It is an official string description of an object that will be called by the built-in function repr() method, and its description must be informative and clear. That is to say__Str__The returned result has strong readability__Repr__The returned results are more accurate.
import datetime
d = datetime.datetime.now()
In: str(d)
OutPut: '2019-08-24 08:12:17.942242' #strong readability
In: repr(d)
OutPut: 'datetime.datetime(2019, 8, 24, 8, 12, 17, 942242)' #more abundant and accurate information
Reference
Magic methods in Python__Str__Related to__Repr__The difference between.