python面向對象編程(2):特殊方法

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()方法

未完待續

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章