repr()和str()方法:
对于一个对象,python中提供了以上两种字符串的表示,它们的作用和repr()、str()、string.format()大体一致。
- 如果需要把一个类的实例变成str对象,就需要实现特殊方法str()
-字符串的format()函数也可以使用这些方法,当我们使用{!r}或者{!s}格式时,我们实际上分别调用了repr()或者str()方法。
class student(object):
def __init__(self,name,grade,score):
self.name=name
self.grade=grade
self.score=score
class collegestudent(student):
def _status(self):
return str(self.name),int(self.grade),int(self.score)
a=collegestudent('daxing','3','59')
print a
print str(a)
结果
<__main__.collegestudent object at 0x383470>
'<__main__.collegestudent object at 0x383470>'
返回的是这个类的地址,并不能从中获得有效的东西
我们需要重写默认的repr()和str()
class student(object):
def __init__(self,name,grade,score):
self.name=name
self.grade=grade
self.score=score
def __str__(self):
return '(student: %s, %s, %s)' %(self.name,self.grade,self.score)
class collegestudent(student):
def _status(self):
return str(self.name),int(self.grade),int(self.score)
a=collegestudent('daxing','3','59')
print a
结果为
(student: daxing, 3, 59)
format()方法
未完待续