Files
Python_CookBook_repo/8.类与对象/1.修改实例的字符串表示.py

24 lines
823 B
Python
Raw Permalink Normal View History

2025-09-10 16:12:45 +08:00
# 想要修改实例的字符串表示,可以在__str__和__repr__方法里做实现
class Pair:
def __init__(self,a,b):
self.a = a
self.b = b
def __repr__(self):
return 'Pair({0.a}, {0.b})'.format(self)
def __str__(self):
return '({0.a}, {0.b})'.format(self)
# format格式复习: {元组下标:填充元素 填充方法(<^>) 填充长度 数据格式(+-.nf d e % 等)}
# 在下面的示例中,!r表示使用__repr__做输出,!s表示使用__str__做输出,这样就不用担心!s和!r顶掉数据格式化字符串的位置了
p =Pair(3, 4)
print("P is {!r}".format(p))
print("P is {!s}".format(p))
# 如果输出不太妙,或者没有输出的方法,就会用<>返回你一段文本,比如文件的返回
path = "5.文件与IO/1.somefile.txt"
f = open(path,"r")
print(f)