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


当前回答

您可以从以下代码中获得一些见解:

class Foo():
    def __repr__(self):
        return("repr")
    def __str__(self):
        return("str")

foo = Foo()
foo #repr
print(foo) #str

其他回答

除了给出的所有答案外,我想补充几点:-

1) 当您只需在交互式python控制台上写入对象名称并按enter键时,就会调用__repr_()。

2) __str__()在使用带有print语句的对象时被调用。

3) 在这种情况下,如果缺少__str__,那么print和任何使用str()的函数都会调用对象的__repr_()。

4) 容器的__str__(),当调用时将执行其包含元素的__repr_()方法。

5) 在__str__()内调用的str()可能会在没有基本情况的情况下递归,并且在最大递归深度上出错。

6) __repr_()可以调用repr(),它将尝试自动避免无限递归,用…替换已经表示的对象。。。。

__repr_在任何地方都使用,但print和str方法除外(当定义了__str__时!)

需要记住的一点是,容器的__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更为健壮。

具有toString方法语言经验的程序员倾向于实现__str__而不是__repr_。如果只在Python中实现这些特殊方法之一,请选择__repr_。

来自Luciano Ramalho的《流利的Python》一书。

__str__可以通过调用str(obj)在对象上调用,并且应该返回一个人类可读的字符串。

__repr_可以通过调用repr(obj)在对象上调用,并且应该返回内部对象(对象字段/属性)

此示例可能有助于:

class C1:pass

class C2:        
    def __str__(self):
        return str(f"{self.__class__.__name__} class str ")

class C3:        
    def __repr__(self):        
         return str(f"{self.__class__.__name__} class repr")

class C4:        
    def __str__(self):
        return str(f"{self.__class__.__name__} class str ")
    def __repr__(self):        
         return str(f"{self.__class__.__name__} class repr")


ci1 = C1()    
ci2 = C2()  
ci3 = C3()  
ci4 = C4()

print(ci1)       #<__main__.C1 object at 0x0000024C44A80C18>
print(str(ci1))  #<__main__.C1 object at 0x0000024C44A80C18>
print(repr(ci1)) #<__main__.C1 object at 0x0000024C44A80C18>
print(ci2)       #C2 class str
print(str(ci2))  #C2 class str
print(repr(ci2)) #<__main__.C2 object at 0x0000024C44AE12E8>
print(ci3)       #C3 class repr
print(str(ci3))  #C3 class repr
print(repr(ci3)) #C3 class repr
print(ci4)       #C4 class str 
print(str(ci4))  #C4 class str 
print(repr(ci4)) #C4 class repr