Python的Object基类__repr__方法

Python的Object基类中,__repr__方法用于生成一个对象的官方字符串表示,通常是一个可执行的表达式。如果未定义__str__,则默认调用__repr__。返回的字符串应尽可能提供有用的信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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方法。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值