str与__str__、repr与__repr__的关系

str

  • 是内置模块定义的类,用于从给定对象创建一个新的字符串对象,即适于人阅读的形式
  • 如果给定参数encoding或errors,则对象必须公开一个将使用给定编码或错误处理程序进行解码的数据缓存区。即处理bytes类型或缓存时,需要使用指定编码或错误处理器来进行解码
  • 除此之外,如果给定对象已定义__str__方法,将返回给定对象的__str__(),否则返回repr(给定对象)
    class str(object):
        """
        str(object='') -> str
        str(bytes_or_buffer[, encoding[, errors]]) -> str
        
        Create a new string object from the given object. If encoding or
        errors is specified, then the object must expose a data buffer
        that will be decoded using the given encoding and error handler.
        Otherwise, returns the result of object.__str__() (if defined)
        or repr(object).
        encoding defaults to sys.getdefaultencoding().
        errors defaults to 'strict'.
        """
    

repr

  • 是内置模块定义的函数,返回对象的规范字符串表现形式,即供解释器读取的形式;对于许多对象类型,生成的字符串满足调用eval函数生成值相等的对象

    def repr(obj): # real signature unknown; restored from __doc__
        """
        Return the canonical string representation of the object.
        
        For many object types, including most builtins, eval(repr(obj)) == obj.
        """
    
    >>> s = '0 + 1'
    >>> repr(s)
    "'0 + 1'"
    >>> eval(repr(s)) == s
    True
    
  • 对于处理未定义__repr__函数的类实例,则返回被定义模块、所属类、内存地址,例如:<__main__.Pear object at 0x7f9bc823b370>

    >>> class Pear:
        	def __init__(self, color):
            	self.color = color
            
    >>> p = Pear('yellowish-white')
    >>> repr(p)
    '<__main__.Pear object at 0x7f9bc823b370>'
    
  • 对于处理定义__repr__函数的类实例,则返回该魔术方法的处理结果

    class Pear:
        def __init__(self, color):
            self.color = color
    
        def __repr__(self):
            return 'repr: Pear(%s)' % self.color
    
    >>> from 内置函数相关.str与repr区别 import Pear
    >>> p = Pear('yellowish-white')
    >>> repr(p)
    'repr: Pear(yellowish-white)'
    
  • str与repr区别,str返回适于人阅读的形式,面向用户,侧重可读性;repr返回供解释器读取的形式,面向解释器或开发者,侧重准确性,比如将repr返回内容复制并定义与对应变量值相等的新变量,用于debug

    >>> s = '0 + 1'
    >>> str(s)
    '0 + 1'
    >>> repr(s)
    "'0 + 1'"
    

__str__

  • 是类中定义的魔术方法,对对象进行字符串处理,返回适于人阅读的形式。当str()、print()、%s、f’{}'和logging打印日志时,会调用该方法
    class Orange:
        def __init__(self, color):
            self.color = color
    
        def __str__(self):
            return 'str: Orange(%s)' % self.color
    
    >>> from 内置函数相关.str与repr区别 import Orange
    >>> o = Orange('yellow')
    >>> str(o)
    'str: Orange(yellow)'
    >>> print(o)
    str: Orange(yellow)
    >>> '%s'%o
    'str: Orange(yellow)'
    >>> f'the color of orange is {o}'
    'the color of orange is str: Orange(yellow)'
    
  • 当调用该魔术方法时,若子类未定义则会向父类寻找(除object类外);若父类未定义则会从子类到父类依次寻找__repr__方法(除object类外);若未找到则调用object类的__str__方法
    class Plants:
        def __init__(self, name):
            self.name = name
    
        def __str__(self):
            return 'Plants(%s)' % self.name
    
    
    class Fruits(Plants):
        def __init__(self, name):
            super(Fruits, self).__init__(name)
    
        def __repr__(self):
            return 'repr: Fruits(%s)' % self.name
    
    >>> from 内置函数相关.str与repr区别 import Fruits
    >>> f = Fruits('banana')
    >>> str(f)
    Plants(banana)
    

__repr__

  • 类中定义的魔术方法,用于在交互模式下提示回应,或者当repr函数处理对象时被调用,返回供解释器读取的形式
    class Apple:
        def __init__(self, color):
            self.color = color
    
        def __str__(self):
            return 'str: Apple(%s)' % self.color
    
        def __repr__(self):
            return 'repr: Apple(%s)' % self.color
    
    >>> from str与repr区别 import Apple
    >>> a = Apple('red')
    >>> a
    repr: Apple(red)
    >>> repr(a)
    'repr: Apple(red)'
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值