官方文档:
Return a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a__ repr()_ method.
和str一样也是返回一个字符串,repr返回的是一个可打印的字符串表示形式。在一个类中,你可以通过定义repr 来返回控制他的返回类型
#repr和str
x='avbc'
print(x) #没有引号
print(str(x)) #没有引号
print(repr(x)) #输出的值是带引号 给python看的
定义_repr_函数
###没有定义__repr__函数的情况
class point:
def __init__(self, x, y):
self.x = x
self.y = y
p = point(10, 10)
print(p)
输出的是下面这串东西,但是我们想让他输出 point(10,10)
<__main__.point object at 0x00000221EDAEE160>
#有__repr__的情况下
class point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return 'point({},{})'.format(self.x, self.y)
p = point(10, 10)
print(p)
输出:
point(10,10)