zoukankan      html  css  js  c++  java
  • 15 __repr__ 与 __strr__

    预览一下两个方法

    >>> class A(object):
    ...     def __repr__(self):
    ...         return "this is __repr__"
    ...     def __str__(self):
    ...         return "this is __str__"
    ...
    >>> a = A()
    >>> a
    this is __repr__
    >>> print(a)
    this is __str__
    >>> 
    

    官方文档

    • Python 3.7.3

    __repr__()

     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 <...some useful 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__() 通常用于调试
    • 它能将对象转化为供解释器读取的形式(字符串)

    __str__()

    object.__str__(self)
    
        Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object. The return value must be a string object.
    
        This method differs from object.__repr__() in that there is no expectation that __str__() return a valid Python expression: a more convenient or concise representation can be used.
    
        The default implementation defined by the built-in type object calls object.__repr__().
    
    • __str__() 是调用 __repr__() 实现的

    举例

    >>> import datetime
    >>> today = datetime.datetime.now()
    >>> today
    datetime.datetime(2019, 4, 11, 20, 45, 8, 463653)
    >>> repr(today)
    'datetime.datetime(2019, 4, 11, 20, 45, 8, 463653)'
    >>> str(today)
    '2019-04-11 20:45:08.463653'
    >>> 
    
    • __repr__() 显示更全面,__str__() 表达更简洁
    • print() 打印对象时,默认调用 __repr__()
      • 若没写,返回 <... object at 0x...>
      • 若有写 __str__(),则调用 __str__()
  • 相关阅读:
    python学习----8.28---单例模式,网络编程
    python学习-----8.27----异常处理,元类
    python学习--8.23
    python学习-----8.22--classmethod和staticmethod
    Python学习---8.21组合,多态,封装
    python学习----8.20面向对象---继承与派生
    Python学习----8.17--面向对象编程
    python成长之旅 一
    python java php语言之间的对比
    python成长之旅
  • 原文地址:https://www.cnblogs.com/yorkyu/p/10693168.html
Copyright © 2011-2022 走看看