• python 的特殊方法 __str__和__repr__


    1.类的实例化返回值

    1 class Foo(object):
    2     def __init__(self):
    3         pass
    4 
    5 obj=Foo()
    6 print(obj)
    View Code

    返回值:<__main__.Foo object at 0x0000000001E9AE48>

    2.__str__方法:

    1 class Foo(object):
    2     def __init__(self):
    3         pass
    4 
    5     def __str__(self):
    6         return "123"
    7 
    8 obj=Foo()
    9 print(obj)
    View Code

    返回值:123

    3.__repr__方法:

     1 class Foo(object):
     2     def __init__(self):
     3         pass
     4 
     5     # def __str__(self):
     6     #     return "123"
     7 
     8     def __repr__(self):
     9         return 'this is repr'
    10 
    11 obj=Foo()
    12 
    13 print(obj)
    View Code

    返回值:this is repr

    4.__str__方法 和 __repr__方法:

     1 class Foo(object):
     2     def __init__(self):
     3         pass
     4 
     5     def __str__(self):
     6         return "this is str"
     7 
     8     def __repr__(self):
     9         return 'this is repr'
    10 
    11 obj=Foo()
    12 
    13 print(obj)
    View Code

    返回值:this is str

    __str__的优先级高于__repr__

    总结:

    __repr__和__str__这两个方法都是用于显示的,__str__是面向用户的,而__repr__面向程序员。

    • 打印操作会首先尝试__str__和str内置函数(print运行的内部等价形式),它通常应该返回一个友好的显示。

    • __repr__用于所有其他的环境中:用于交互模式下提示回应以及repr函数,如果没有使用__str__,会使用print和str。它通常应该返回一个编码字符串,可以用来重新创建对象,或者给开发者详细的显示。

    当我们想所有环境下都统一显示的话,可以重构__repr__方法;当我们想在不同环境下支持不同的显示,例如终端用户显示使用__str__,而程序员在开发期间则使用底层的__repr__来显示,实际上__str__只是覆盖了__repr__以得到更友好的用户显示。

  • 相关阅读:
    产品流程关键点分析
    Hadoop分布式文件系统(HDFS)设计
    什么是产品经理
    转:互联网产品开发流程
    如何用PHP/MySQL为 iOS App 写一个简单的web服务器(译) PART1
    mobile app 与server通信的四种方式
    Android: Client-Server communication
    Android: Client-Server communication by JSON
    Samba 源码解析之SMBclient命令流
    Samba 源码解析之内存管理
  • 原文地址:https://www.cnblogs.com/zoe233/p/7600853.html
Copyright © 2020-2023  润新知