zoukankan      html  css  js  c++  java
  • python类中方法__str__()和__repr__()简单粗暴总结

    在交互式模式下,类中同时实现__str__()和__repr__()方法:

    直接输入实例名称显示repr返回的类容; 

    用print打印实例名称显示str返回的内容;

    >>> class Test:
    ...     def __repr__(self):
    ...         return 'Test -> return repr'
    ...     def __str__(self):
    ...         return 'Test -> return str'
    ...     
    >>> t = Test()
    >>> t
    Test -> return repr
    >>> print(t)
    Test -> return str

    在交互式模式下,如果只实现了__repr__()方法则:

    直接输入实例名称和print打印都显示repr返回的内容。

    >>> class Test:
    ...     def __repr__(self):
    ...         return 'Test -> return repr'
    ... 
    >>> t = Test()
    >>> t
    Test -> return repr
    >>> print(t)
    Test -> return repr

    在交互式模式下,如果只实现了__str__()方法则:

    直接输入实例名称返回的是对象地址信息。

    而print打印输出的是str返回的内容。

    >>> class Test:
    ...      def __str__(self):
    ...          return 'Test -> return str'
    ...  
    >>> t = Test()
    >>> t
    <__main__.Test object at 0x00000234355D43C8>
    >>> print(t)
    Test -> return str

    总结:

    一般情况下,让repr成为str的一个别名输出相同的内容就可以了。

    >>> class Test:
    ...     def __str__(self):
    ...         return 'Test -> return str'
    ...     __repr__ = __str__
    ...     
    >>> t = Test()
    >>> t
    Test -> return str
    >>> print(t)
    Test -> return str
  • 相关阅读:
    webpack入门(1)
    react基础(2)
    react基础(1)
    react入门(5)
    react入门(4)
    react入门(3)
    webstorm出现黑色块光标
    微信小程序——组件(二)
    微信小程序——组件(一)
    react-native 在Xcode上传到iTunes Connect里报错
  • 原文地址:https://www.cnblogs.com/bryant24/p/11428987.html
Copyright © 2011-2022 走看看