Python的Object基类__repr__方法
Python基类的內建方法__repr__是执行一个官方的(或者正式的)代表一个对象的字符串,也就是说可以将字符串转换成一个Python对象。如果可能的话,最好是有效的表达式字符串。如果不可能的话,那需要返回<...someusefuldescription...>类似这样的字符串,必须返回字符串。
如果一个类定义了__repr__,而没有定义__str__方法的时,那么就执行__repr__,创建一个实例。
Python3.4文档:
object. __repr__ ( self )
Called by the repr() built-in function to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form<...someuseful description...> should be returned. The return value must be a string object. If a class defines__repr__() but not__str__(), then__repr__() is also used when an “informal” string representation of instances of that class is required.
This is typically used for debugging, so it is important that the representation is information-rich and unambiguous
创建一个类来演示repr方法:
class Node:
def __init__(self,value,flag=1):
self._value = value
self._children = []
self._flag = flag
def add_child(self,node):
self._children.append(node)
def __repr__(self):
return 'Node({!r})'.format(self._value)
if __name__ == '__main__':
n1 = Node(0)
t1 = repr(t)
print('object n1 定义 :',t,' object n2 定义 ::',t1)
print('object n1 id :',id(t),' object n2 id ::',id(t1))
输出:
object n1 定义 : Node(0) object n2 定义 :: Node(0)
object n1 id : 50620048 object n2 id :: 50619584
这里就显示了这两个对象是不同的,在内存中的id不一致就可以确定。
__repr__是类的內建方法,所有的类都是继承自Object类,因此在外部调用时,需要使用repr函数,好比Node类通过重写__repr__,从而重写了repr,
但是只是对Node类的实例有效。
如果自定义类覆盖了这个方法那么在使用str时,底层调用的也是这个方法。
当然并不影响系统的str方法。