美文网首页
python--str和repr的区别

python--str和repr的区别

作者: 极光火狐狸 | 来源:发表于2018-09-21 01:37 被阅读19次
    
    
    class A(object):
    
        def __init__(self):
            self.lang = "python"
    
        def __repr__(self):
            return "<{} lang={}>".format(self.__class__.__name__, self.lang)
    
        def __str__(self):
            return "<{} language={}>".format(self.__class__.__name__, self.lang)
    
    
    if __name__ == '__main__':
        a = A()
        b = repr(a)
        c = str(a)
    
        print("{:<50} {}".format(a, type(a)))
        print("{:<50} {}".format(b, type(b)))
        print("{:<50} {}".format(c, type(c)))
    
        # output
        # <A language=python>                                <class '__main__.A'>
        # <A lang=python>                                    <type 'str'>
        # <A language=python>                                <type 'str'>
    
    

    相关文章

      网友评论

          本文标题:python--str和repr的区别

          本文链接:https://www.haomeiwen.com/subject/trionftx.html