We all know that Python’s built-in function repr() can convert objects in the form of strings Express it so that we can identify it easily. This is the "string representation". repr() obtains the string representation of an object through the special method __repr__. If __repr__ is not implemented, when we print a vector instance to the console, the resulting string may be
>>> class Example: pass >>> print(str(Example())) <__main__.Example object at 0x10a514f98> >>> print(repr(Example())) <__main__.Example object at 0x1088eb438> >>> >>> str(Example) "<class '__main__.Example'>" >>> repr(Example()) '<__main__.Example object at 0x1088eb438>'
Next let’s take a look at the similarities and differences between **__str__** and **__repr__**. According to the official Python documentation:
You are confused about formal and informal formats, right? It’s okay, let’s go on to see:
>>> x = 4 >>> repr(x) '4' >>> str(x) '4' >>> y = 'pythonic' >>> repr(y) "'pythonic'" >>> str(y) 'pythonic' >>> z = '4' >>> repr(z) "'4'" >>> str(z)# 注意,此处的输出结果形式跟str(x)一样,但x和z的类型并不一样 '4' >>> str(x) == str(z) True >>> repr(x) == repr(z) False >>> str(4) == str("4") True >>> repr(4) == repr("4") False
When x=4, when x is an integer type, the return of calling str() and repr() The result is the same,
And when y is a string type, the result of repr(y) is a "formal" string representation, while the result of str(y) is "informal" . str() allows us to understand the content of the object most quickly and is more readable.
>>> import datetime >>> d = datetime.datetime.now() >>> str(d) '2020-04-04 20:47:46.525245' >>> repr(d) 'datetime.datetime(2020, 4, 4, 20, 47, 46, 525245)' >>>
It can be seen that repr() can better display the type, value and other information of the object, and the object description is clear of.
It is called when the str() function is used, or when an object is printed using the print function, and the string it returns is more friendly to end users.
class Student(): def __init__(self, name): self.name = name def __str__(self): return "Name:" + self.name def __repr__(self): return "姓名:" + self.name class_one = Student("Alice") print(class_one) print(str(class_one)) print(repr(class_one))
Output results:
Name:Alice Name:Alice 姓名:Alice
Common points: They are all used To output an object
Difference:
The above is the detailed content of A thorough understanding of __str__ and __repr__ in Python in one article. For more information, please follow other related articles on the PHP Chinese website!