python: 理解__str__

來源:互聯網
上載者:User

以下是我的理解,如果有錯我的地方。請務必告訴我。不勝感激!

在python語言裡,__str__一般是格式是這樣的。

class A:

def __str__(self):

return "this is in str"

事實上,__str__是被print函數調用的,一般都是return一個什麼東西。這個東西應該是以字串的形式表現的。如果不是要用str()函數轉換。當你列印一個類的時候,那麼print首先調用的就是類裡面的定義的__str__,比如:str.py

#!/usr/bin/env python                                                                                                                                                                                 class strtest:    def __init__(self):        print "init: this is only test"    def __str__(self):        return "str: this is only test"if __name__ == "__main__":    st=strtest()    print st

$./str.py

init: this is only test

str: this is only test

從上面例子可以看出,當列印strtest的一個執行個體st的時候,__str__函數被調用到。

其實,python裡面的對象基本上都預設有個__str__供print函數所用。比如字典裡的__str__,見紅色部分:

>>> dir({})
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

>>> t={}

>>> t['1'] = "hello"

>>> t['2'] = "world"
>>> t   #等於 print t
{'1': 'hello', '2': 'world'}
>>> t.__str__()
"{'1': 'hello', '2': 'world'}"

大家可以看到一個字典,print t 和 t.__str__()是一樣的。只不過__str__()將字典內容以字串形式輸出。

看看下面的例子,如果在函數__str__裡返回的不是字串,請看str1.py

#!/us/bin/env/python                                                                                                                                                                                        #__metaclass__ = type#if __name__ == "__main__":class strtest:    def __init__(self):        self.val = 1    def __str__(self):        return self.valif __name__ == "__main__":    st=strtest()    print st

$./str1.py

Traceback (most recent call last):
  File "./str.py", line 12, in <module>
    print st
TypeError: __str__ returned non-string (type int)

錯誤的資訊提示:__str__返回了一個非字串。這時候我們應該這樣做:請看str2.py

#!/usr/bin/env python                                                                                                                                                                                        #__metaclass__ = type#if __name__ == "__main__":class strtest:    def __init__(self):        self.val = 1    def __str__(self):        return str(self.val)if __name__ == "__main__":    st=strtest()    print st

$./str2.py

1

我們用str()將整型變為了字元型。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.