python Class:物件導向進階編程 __str__ / __repr__

來源:互聯網
上載者:User

標籤:rip   fun   lib   vpd   pad   sig   shadow   expr   eve   

其實:__str__ 與 __repr__效果一樣, 人們說:__str__ 是面向使用者的, 而__repr__是面向程式員的, 轟朵你?


官網解釋:

  • object.__repr__(self)?

  • Called by the repr() built-in function and by string conversions (reversequotes) to compute the “official” string representation of an object.  If at allpossible, this should look like a valid Python expression that could be used torecreate an object with the same value (given an appropriate environment).  Ifthis is not possible, a string of the form <...some useful description...>should be returned.  The return value must be a string object. If a classdefines __repr__() but not __str__(), then __repr__() is alsoused when an “informal” string representation of instances of that class isrequired.


  • object.__str__(self)?

  • Called by the str() built-in function and by the printstatement to compute the “informal” string representation of an object.  Thisdiffers from __repr__() in that it does not have to be a valid Pythonexpression: a more convenient or concise representation may be used instead.The return value must be a string object.


看瞭解釋,哪裡說是面向使用者,哪裡又說面向程式員了????看到加粗字了沒有,看到下滑線了沒有???這裡說的是作用於所有人好嘛!!!如果非要以自己的職位來說,好吧,好像是這麼一回事,真是 淫穢  隱晦的表達。


不說了,先小試一下:

#!/usr/bin/python
# -*- coding: utf-8 -*-

class Student(object):
     def __init__(self, name):
         self.hah = name
        
class Str(Student):
     def __str__(self):
       return  'Str (name: %s)' %self.hah


class Repr(Student):
     def __repr__(self):
       return  'Repr(name: %s)' % self.hah


s = Student('Michael')
print s.hah

print Str('you')

print Repr('me')


最近非常的狂,不,不是最近,而是這個階段的我,非常喜歡懟,如果我表達不好,那真是 抱歉了 。。。 你有理,你也來懟我啊,來啊,相互傷害啊!!!

python Class:物件導向進階編程 __str__ / __repr__

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.