Python中__str__和__repr_之间有什么区别?


当前回答

__str__必须返回字符串对象,而__repr_可以返回任何python表达式。如果缺少__str__实现,则__repr_函数用作回退。如果缺少__repr_函数实现,则没有回退。如果__repr_函数返回对象的String表示,我们可以跳过__str__函数的实现。

资料来源:https://www.journaldev.com/22460/python-str-repr-functions

其他回答

>>> print(decimal.Decimal(23) / decimal.Decimal("1.05"))
21.90476190476190476190476190
>>> decimal.Decimal(23) / decimal.Decimal("1.05")
Decimal('21.90476190476190476190476190')

当对decimal.decimal(23)/decimal.Ddecimal(“1.05”)的结果调用print()时,将打印原始数字;此输出为字符串形式,可以使用__str__()实现。如果我们简单地输入表达式,我们会得到一个decimal.decimal输出-这个输出是以表示形式的,可以用__repr_()实现。所有Python对象都有两种输出形式。字符串形式设计为人类可读。表示形式被设计为生成输出,如果将其提供给Python解释器,将(在可能的情况下)再现所表示的对象。

需要记住的一点是,容器的__str__使用包含的对象的__repr_。

>>> from datetime import datetime
>>> from decimal import Decimal
>>> print (Decimal('52'), datetime.now())
(Decimal('52'), datetime.datetime(2015, 11, 16, 10, 51, 26, 185000))
>>> str((Decimal('52'), datetime.now()))
"(Decimal('52'), datetime.datetime(2015, 11, 16, 10, 52, 22, 176000))"

Python比可读性更倾向于明确性,元组的__str__调用调用所包含对象的__repr_,即对象的“形式”表示。虽然正式表示比非正式表示更难理解,但它是明确的,并且对bug更为健壮。

简单地说:

__str__用于显示对象的字符串表示形式,以便其他人轻松读取。

__repr_用于显示对象的字符串表示。

假设我想创建一个分数类,其中分数的字符串表示为“(1/2)”,对象(分数类)表示为“分数(1,2)”

因此,我们可以创建一个简单的Fraction类:

class Fraction:
    def __init__(self, num, den):
        self.__num = num
        self.__den = den

    def __str__(self):
        return '(' + str(self.__num) + '/' + str(self.__den) + ')'

    def __repr__(self):
        return 'Fraction (' + str(self.__num) + ',' + str(self.__den) + ')'



f = Fraction(1,2)
print('I want to represent the Fraction STRING as ' + str(f)) # (1/2)
print('I want to represent the Fraction OBJECT as ', repr(f)) # Fraction (1,2)

repr()用于调试或日志。它用于开发人员理解代码。另一方面,str()用户用于非开发人员(QA)或用户。

class Customer:
    def __init__(self,name):
        self.name = name
    def __repr__(self):
        return "Customer('{}')".format(self.name)
    def __str__(self):
        return f"cunstomer name is {self.name}"

cus_1 = Customer("Thusi")
print(repr(cus_1)) #print(cus_1.__repr__()) 
print(str(cus_1)) #print(cus_1.__str__())

来自effbot的(非官方)Python参考Wiki(存档副本):

__str__“计算对象的“非正式”字符串表示。这与__repr_不同,因为它不必是有效的Python表达式:可以使用更方便或更简洁的表示。”