zoukankan      html  css  js  c++  java
  • __str__和__repr__的区别

    有时候我们想让屏幕打印的结果不是对象的内存地址,而是它的值或者其他可以自定义的东西,以便更直观地显示对象内容,可以通过在该对象的类中创建或修改__str__()__repr__()方法来实现(显示对应方法的返回值)
    注意:__str__()方法和__repr__()方法的返回值只能是字符串!

    关于调用两种方法的时机

    • 使用print()时
    • 使用%sf'{}'拼接对象时
    • 使用str(x)转换对象x时

    在上述三种场景中,会优先调用对象的__str__()方法;若没有,就调用__repr__()方法;若再没有,则显示其内存地址。

    特别地,对于下面两种场景:

    • %r进行字符串拼接时
    • repr(x)转换对象x时

    则会调用这个对象的__repr__()方法;若没有,则不再看其是否有__str__()方法,而是显示其内存地址。
    Django中打印queryset时,会调用__repr__方法

    class A(object): pass
    class B(object):
        def __str__(self):
            return '1'
    class C(object):
        def __repr__(self):
            return '2'
    class D(object):
        def __str__(self):
            return '3'
        def __repr__(self):
            return '4'
    a=A()
    b=B()
    c=C()
    d=D()
    print(a,b,c,d)
    print('%s,%s,%s,%s'%(a,b,c,d))
    print('%r,%r,%r,%r'%(a,b,c,d))
    print(f'{a},{b},{c},{d}')
    print(str(a),str(b),str(c),str(d))
    print(repr(a),repr(b),repr(c),repr(d))
    ------------------------------------------------------
    <__main__.A object at 0x0000000002419630> 1 2 3
    <__main__.A object at 0x0000000002419630>,1,2,3
    <__main__.A object at 0x0000000002419630>,<__main__.B object at 0x0000000002419A58>,2,4
    <__main__.A object at 0x0000000002419630>,1,2,3
    <__main__.A object at 0x0000000002419630> 1 2 3
    <__main__.A object at 0x0000000002419630> <__main__.B object at 0x0000000002419A58> 2 4
    
  • 相关阅读:
    微信小程序自定义navigationBar
    微信小程序-自动定位并将经纬度解析为具体地址
    a conexant audio couldnot befound
    平衡二叉树(AVL)java实现
    二叉树的各种非递归遍历
    选择排序
    快速排序
    冒泡排序
    数组洗牌
    haffman树c实现
  • 原文地址:https://www.cnblogs.com/zyyhxbs/p/11184094.html
Copyright © 2011-2022 走看看