2025-09-10:仓库迁移
This commit is contained in:
23
8.类与对象/1.修改实例的字符串表示.py
Normal file
23
8.类与对象/1.修改实例的字符串表示.py
Normal file
@@ -0,0 +1,23 @@
|
||||
# 想要修改实例的字符串表示,可以在__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)
|
Reference in New Issue
Block a user