[英]Why can __repr__ function use repr() in itself when defining a class?(Python)
class Link:
def __init__(self, first, rest=empty):
assert rest is Link.empty or isinstance(rest, Link)
self.first = first
self.rest = rest
def __repr__(self):
if self.rest is not Link.empty:
rest_repr = ', ' + repr(self.rest)
else:
rest_repr = ''
return 'Link(' + repr(self.first) + rest_repr + ')'
def __str__(self):
string = '<'
while self.rest is not Link.empty:
string += str(self.first) + ' '
self = self.rest
return string + str(self.first) + '>'
This is defining code of Link(ielinked list).And the __repr __function's output is like这是链接的定义代码(即链表)。而__repr __函数的output就像
>>> s = Link(5,Link(6))
>>> s # Displays the contents of repr(s)
Link(5, Link(6))
But I cann't understand why the __repr__ function can use repr(self.first)
in itself.I think that would cause inifinite loop.但我不明白为什么 __repr__ function 本身可以使用repr(self.first)
。我认为这会导致无限循环。
I wonder:Is the repr
function a built-in funciton in Python even though I am defining the __repr__ function?(Just like the str
can be used in the __str__ function?) I wonder:Is the repr
function a built-in funciton in Python even though I am defining the __repr__ function?(Just like the str
can be used in the __str__ function?)
def __repr__(self):
if self.rest is not Link.empty:
rest_repr = ', ' + repr(self.rest)
Look at this piece of code, what do you notice?看看这段代码,你注意到了什么?
Exactly: you are using repr(self.rest)
, which is equivalent to self.rest.__repr__()
.确切地说:您正在使用repr(self.rest)
,相当于self.rest.__repr__()
。
In other words you aren't calling repr
on an instance of Link
, but just on an attribute of it.换句话说,您不是在Link
的实例上调用repr
,而只是在它的一个属性上调用。 So you aren't calling Link.__repr__
into its body, don't worry.因此,您不会将Link.__repr__
调用到它的主体中,不用担心。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.