python--str和repr的区别

2018-09-21  本文已影响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'>

上一篇 下一篇

猜你喜欢

热点阅读