Python中__str__和__repr_之间有什么区别?
当前回答
基本上__str__或str()用于创建人类可读的输出,这些输出必须面向最终用户。另一方面,repr()或__repr_主要返回对象的规范字符串表示,用于调试和开发,帮助程序员。
其他回答
str-从给定对象创建一个新的字符串对象。
repr-返回对象的规范字符串表示形式。
差异:
str():
使对象可读为最终用户生成输出
repr():
需要复制对象的代码为开发人员生成输出
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__())
简而言之:
class Demo:
def __repr__(self):
return 'repr'
def __str__(self):
return 'str'
demo = Demo()
print(demo) # use __str__, output 'str' to stdout
s = str(demo) # __str__ is used, return 'str'
r = repr(demo) # __repr__ is used, return 'repr'
import logging
logger = logging.getLogger(logging.INFO)
logger.info(demo) # use __str__, output 'str' to stdout
from pprint import pprint, pformat
pprint(demo) # use __repr__, output 'repr' to stdout
result = pformat(demo) # use __repr__, result is string which value is 'str'
__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
简单地说:
__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)