[转载]python中__str__ __repr__的用法

个人理解来说,__str__是在类print的时候,让展示信息更加便于使用者阅读,__repr__和__str__类似,不用print也能展示出类的相关信息。(有点肤浅,哈哈)

例子

    >>> class A:
        pass
     
    >>> a1 = A()
    >>> a1
    <__main__.A object at 0x000000000302C358>
     
    >>> print(a1)
    <__main__.A object at 0x000000000302C358>
     
     

    >>> class A:
        def __str__(self):        #__str__使用:被打印的时候需要以字符串的形式输出的时候,就会找到这个方法,并将返回值打印出来
            return "我是一个字符串"                                                                      
    #要想显示对象的属性,可以(1)return 后加上你想要格式化输出的属性,比如: return "%d %s" % (int("123"), str(123))                                                                   
    #(2)利用字符串的format方法,比如:"{},{}".format(1,2)    
    >>> a1 = A()
    >>> a1
    <__main__.A object at 0x00000000033712E8>
     
    >>> print(a1)
    我是一个字符串
     
     
     

    >>> class A:
        def __repr__(self):   #返回一个可以用来表示对象的可打印字符串
            return "我是一个字符串"
     
        
    >>> a1 = A()
    >>> a1
    我是一个字符串
     
    >>> print(a1)
    我是一个字符串

    >>> class A:
        def __str__(self):
            return "__str__"
        def __repr__(self):   
            return "__repr__"
     
        
    >>> a1 = A()
    >>> a1
    __repr__
    >>> print(a1)
    __str__

此例表明:同时定义 __repr__ 方法和 __str__ 方法时,print() 方法会调用 __str__ 方法。

 

 
关系

__str__ 方法其实调用了 __repr__ 方法。

 
使用

在 sof 上的解释是:

__repr__ 目的是为了表示清楚,是为开发者准备的。

__str__ 目的是可读性好,是为使用者准备的。

我的理解是 __repr__ 应该尽可能的表示出一个对象来源的类以及继承关系,方便程序员们了解这个对象。而 __str__ 就简单的表示对象,而不要让不懂编程的以为输出的是 bug。

    >>> import datetime
    >>> today = datetime.datetime.now()
    >>> str(today)
    '2012-03-14 09:21:58.130922'
    >>> repr(today)
    'datetime.datetime(2012, 3, 14, 9, 21, 58, 130922)'

上表是来自 bitoffdev 的回答。

我们可以看到 str(today) 输出的很正常,哪个都看得懂。但是 repr(today) 的输出对不懂编程的就来说有点奇怪了,只懂一丢丢的还可能会以为自己搞出了啥幺蛾子呢。但是这对于有点经验的人来说这个就表示 today 对象是由 datetime 类实例化出来的。

 
官方文档

    repr(object)

    Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. 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(object='')

    Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. If no argument is given, returns the empty string, ''.

 
参考

http://blog.csdn.net/luckytanggu/article/details/53649156

https://www.cnblogs.com/superxuezhazha/p/5746922.html

http://blog.csdn.net/DucklikeJAVA/article/details/73478307
---------------------
作者:在到处之间找我
来源:CSDN
原文:https://blog.csdn.net/sinat_41104353/article/details/79254149
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值