字符串输出的两种调用方法

class ReprStr:
    def __repr__(self):  # 命令行交互环境,输入对象名 回车,调用此方法。   字符串真正的样子
        return "返回的是 __repr__ 方法"

    def __str__(self):  # 用 print 输出变量时,调用此方法。   经过Python优化,更便于人类阅读的样式
        return "返回的是 __str__ 方法"


>>> reprstr = ReprStr()
>>> reprstr
返回的是 __repr__ 方法
>>> print(reprstr)
返回的是 __str__ 方法

>>> a = 'hello'
>>> a
'hello'
>>> print(a)
hello

>>> b = 'D:\Python\my'
>>> b
'D:\\Python\\my'
>>> print(b)
D:\Python\my

>>> print(repr(b))
'D:\\Python\\my'

>>> b.__str__()
'D:\\Python\\my'

>>> b.__repr__()
"'D:\\\\Python\\\\my'"

  

posted @ 2023-06-05 17:10  sangern  阅读(15)  评论(0)    收藏  举报