<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                ## 問題 你想通過 `format()` 函數和字符串方法使得一個對象能支持自定義的格式化。 ## 解決方案 為了自定義字符串的格式化,我們需要在類上面定義 `__format__()` 方法。例如: _formats = { 'ymd' : '{d.year}-{d.month}-{d.day}', 'mdy' : '{d.month}/{d.day}/{d.year}', 'dmy' : '{d.day}/{d.month}/{d.year}' } class Date: def __init__(self, year, month, day): self.year = year self.month = month self.day = day def __format__(self, code): if code == '': code = 'ymd' fmt = _formats[code] return fmt.format(d=self) 現在 `Date` 類的實例可以支持格式化操作了,如同下面這樣: >>> d = Date(2012, 12, 21) >>> format(d) '2012-12-21' >>> format(d, 'mdy') '12/21/2012' >>> 'The date is {:ymd}'.format(d) 'The date is 2012-12-21' >>> 'The date is {:mdy}'.format(d) 'The date is 12/21/2012' >>> ## 討論 `__format__()` 方法給Python的字符串格式化功能提供了一個鉤子。這里需要著重強調的是格式化代碼的解析工作完全由類自己決定。因此,格式化代碼可以是任何值。例如,參考下面來自 `datetime` 模塊中的代碼: >>> from datetime import date >>> d = date(2012, 12, 21) >>> format(d) '2012-12-21' >>> format(d,'%A, %B %d, %Y') 'Friday, December 21, 2012' >>> 'The end is {:%d %b %Y}. Goodbye'.format(d) 'The end is 21 Dec 2012. Goodbye' >>> 對于內置類型的格式化有一些標準的約定。可以參考 [string模塊文檔](https://docs.python.org/3/library/string.html) 說明。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看