乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      python對象及面向?qū)ο蠹夹g(shù)詳解

       imelee 2016-12-15

      本文實例講述了python對象及面向?qū)ο蠹夹g(shù)。分享給大家供大家參考,具體如下:

      1 先看一個例子. 本章將講解這個例子程序:

      文件: fileinfo.py:

      """Framework for getting filetype-specific metadata.
      Instantiate appropriate class with filename. Returned object acts like a
      dictionary, with key-value pairs for each piece of metadata.
        import fileinfo
        info = fileinfo.MP3FileInfo("/music/ap/mahadeva.mp3")
        print "\n".join(["%s=%s" % (k, v) for k, v in info.items()])
      Or use listDirectory function to get info on all files in a directory.
        for info in fileinfo.listDirectory("/music/ap/", [".mp3"]):
          ...
      Framework can be extended by adding classes for particular file types, e.g.
      HTMLFileInfo, MPGFileInfo, DOCFileInfo. Each class is completely responsible for
      parsing its files appropriately; see MP3FileInfo for example.
      """
      import os
      import sys
      from UserDict import UserDict
      def stripnulls(data):
        "strip whitespace and nulls"
        return data.replace("{post.content}", "").strip()
      class FileInfo(UserDict):
        "store file metadata"
        def __init__(self, filename=None):
          UserDict.__init__(self)
          self["name"] = filename
      class MP3FileInfo(FileInfo):
        "store ID3v1.0 MP3 tags"
        tagDataMap = {"title"  : ( 3, 33, stripnulls),
               "artist" : ( 33, 63, stripnulls),
               "album"  : ( 63, 93, stripnulls),
               "year"  : ( 93, 97, stripnulls),
               "comment" : ( 97, 126, stripnulls),
               "genre"  : (127, 128, ord)}
        def __parse(self, filename):
          "parse ID3v1.0 tags from MP3 file"
          self.clear()
          try:
            fsock = open(filename, "rb", 0)
            try:
              fsock.seek(-128, 2)
              tagdata = fsock.read(128)
            finally:
              fsock.close()
            if tagdata[:3] == "TAG":
              for tag, (start, end, parseFunc) in self.tagDataMap.items():
                self[tag] = parseFunc(tagdata[start:end])
          except IOError:
            pass
        def __setitem__(self, key, item):
          if key == "name" and item:
            self.__parse(item)
          FileInfo.__setitem__(self, key, item)
      def listDirectory(directory, fileExtList):
        "get list of file info objects for files of particular extensions"
        fileList = [os.path.normcase(f)
              for f in os.listdir(directory)]
        fileList = [os.path.join(directory, f)
              for f in fileList
              if os.path.splitext(f)[1] in fileExtList]
        def getFileInfoClass(filename, module=sys.modules[FileInfo.__module__]):
          "get file info class from filename extension"
          subclass = "%sFileInfo" % os.path.splitext(filename)[1].upper()[1:]
          return hasattr(module, subclass) and getattr(module, subclass) or FileInfo
        return [getFileInfoClass(f)(f) for f in fileList]
      if __name__ == "__main__":
        for info in listDirectory("/music/_singles/", [".mp3"]):
          print "\n".join(["%s=%s" % (k, v) for k, v in info.items()])
          print
      
      

      2 使用 from module import 導(dǎo)入模塊

      我們以前學(xué)的導(dǎo)入模塊是用下邊的語法:

      import 模塊名

      這樣在需要使用該模塊中的東西時. 要通過 模塊名.XXX 的形式. 例如:

      >>> import types
      >>> types.FunctionType
      <type 'function'>
      >>> FunctionType
      
      

      如果不用模塊名而直接使用其中的名字則出錯. 所以打印:

      Traceback (most recent call last):
       File "<interactive input>", line 1, in <module>
      NameError: name 'FunctionType' is not defined
      
      

      現(xiàn)在看看另一種導(dǎo)入模塊中名字的語法:

      from 模塊名 import 名字

      或者用

      from 模塊名 import *

      例如:

      >>> from types import FunctionType
      
      

      這樣導(dǎo)入的名字就可以不通過模塊名而直接使用. 如:

      >>> FunctionType
      <type 'function'>
      
      

      3 類的定義

      定義類的語法:

      class 類名:
          pass

      或者

      class 類名(基類列表) :
          pass

      其中的 pass 是Python的關(guān)鍵字. 表示什么也不做.

      類也可以有類文檔. 如果有的話. 他應(yīng)該是類定義中的第一個東西. 如:

      class A(B) :
        " this is class A. "
      
      

      類的構(gòu)造函數(shù)為:

      __init__
      
      

      不過. 準(zhǔn)確的說. 這只能算是創(chuàng)建該類對象后. 自動執(zhí)行的方法. 當(dāng)執(zhí)行這個函數(shù)時. 對象已初始化了.

      例如:

      class A(B) :
        "this is class A. "
        def __init__ (self):
          B.__init__(self)
      
      

      這里為類A 定義了一個構(gòu)造方法. 并且在其中調(diào)用了基類B的構(gòu)造方法.

      要注意的是. 在Python中. 構(gòu)造派生類時. 并不會"自動"的調(diào)用基類的構(gòu)造方法. 需要的話必須顯式寫出.

      所有的類方法. 第一個參數(shù)都是用來接收this指針. 習(xí)慣上這個參數(shù)的名字是 self.

      調(diào)用時不要傳遞這個參數(shù). 它會自動被加上的.

      但是在象上邊的構(gòu)造函數(shù)中. 調(diào)用基類的__init()時. 這個參數(shù)必須顯式給出.

      4 類的實例化

      實例化一個類和其它語言相似. 只把它的類名當(dāng)作一個函數(shù)調(diào)用就行了. 而沒有其它語言的new之類.

      類名(參數(shù)表)

      其中參數(shù)表中不必給出__init__的第一個參數(shù)self.

      例如:

      a = A()

      我們可以通過類或類的實例查看該類的文檔. 這通過它們的__doc__屬性. 如:

      >>> A.__doc__
      'this is class A. '
      >>> a.__doc__
      'this is class A. '
      
      

      我們也可以通過類的實例來得到它的類. 這通過它的__class__屬性. 如:

      >>> a.__class__
      <class __main__.A at 0x011394B0>
      
      

      創(chuàng)建了類的實例后. 我們不用擔(dān)心回收的問題. 垃圾回收會根據(jù)引用計數(shù)自動銷毀不用的對象.

      Python中. 類的數(shù)據(jù)成員也沒有專門的聲明語句. 而是在賦值的時候"突然產(chǎn)生"的. 例如:

      class A :
        def __init__(self) :
          self.data = []
      
      

      這時. 就自動讓data作為類A的成員了.

      之后在類的定義內(nèi). 要使用類中的成員變量或成員方法. 都要用 self.名字 來限定.

      所以一般要產(chǎn)生數(shù)據(jù)成員. 在任何方法中對 self.成員名字 賦值即可.

      不過. 在__init__方法中對所有數(shù)據(jù)屬性都賦一個初始值. 是一個好習(xí)慣.

      Python不支持函數(shù)重載.

      這里再說說代碼縮進(jìn). 實際上. 如果一個代碼塊只有一句. 可以直接放在 冒號 后邊. 而不需要換行縮進(jìn)格式.

      6 專用類方法

      和普通的方法不同. 在類中定義專用方法后. 并不要你顯式的調(diào)用它們. 而是在某些時候有Python自動調(diào)用.

      獲得和設(shè)置數(shù)據(jù)項.

      這需要在類中定義 __getitem__ 和 __setitem__ 方法.

      例如:

      >>> class A:
      ... def __init__(self):
      ...  self.li = range(5)
      ... def __getitem__(self, i):
      ...  return self.li[-i]
      ...
      >>> a = A()
      >>> print a[1]
      
      

      這里的 a[1] 就調(diào)用了 __getitem__ 方法. 它等于 a.__getitem__(1)

      與__getitem__方法類似的有 __setitem__

      例如在上邊的A類中定義:

      def __setitem__(self, key, item):
        self.li[key] = item
      
      

      然后調(diào)用這個方法如下:

      a[1] = 0 它等于調(diào)用 a.__setitem__(1, 0)

      7 高級專用類方法

      和 __getitem__ __setitem__ 類似. 還有一些特殊的專用函數(shù). 如下:

      def __repr__(self): return repr(self.li)
      
      

      這個專用方法用來本對象的字符串表示. 調(diào)用它是通過內(nèi)置函數(shù)repr(). 如

      repr(a)
      
      

      這個repr()可以作用在任何對象上.

      實際上. 在交互窗口中. 只要輸入 變量名 回車. 就用repr顯示變量的值.

      def __cmp__(self, x):
        if isinstance(x, A): return cmp(self.li, x.li)
      
      

      它用來比較兩個實例 self 和 x 是否相等. 調(diào)用它時如下:

      a = A()
      b = A()
      a == b
      
      

      這里比較 a和b是否相等. 和調(diào)用 a.cmp(b) 一樣

      def __len__(self): return len(self.li)
      
      

      它用來返回對象的長度. 在使用 len(對象) 的時候會調(diào)用它.
      用它可以指定一個你希望的邏輯長度值.

      def __delitem__(self, key): del self.li[key]
      
      

      在調(diào)用 del 對象[key] 時會調(diào)用這個函數(shù).

      8 類屬性

      類屬性指的是象c++中靜態(tài)成員一類的東西.

      Python中也可以有類屬性. 例如:

      class A :
        l = [1, 2, 3]
      
      

      可以通過類來引用(修改). 或者通過實例來引用(修改). 如:

      A.l
      
      

      a.__class__.l
      
      

      9 私有函數(shù)

      Python中也有"私有"這個概念:

      私有函數(shù)不可以從它們的模塊外邊被調(diào)用.
      私有類方法不能從它們的類外邊被調(diào)用.
      私有屬性不能從它們的類外邊被訪問.

      Python中只有私有和公有兩種. 沒有保護(hù)的概念. 而區(qū)分公有還是私有是看函數(shù). 類方法. 類屬性的名字.

      私有的東西的名字以 __ 開始. (但前邊說的專用方法(如__getitem__)不是私有的).

      更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python面向?qū)ο蟪绦蛟O(shè)計入門與進(jìn)階教程》、《Python文件與目錄操作技巧匯總》、《Python圖片操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》及《Python入門與進(jìn)階經(jīng)典教程

      希望本文所述對大家Python程序設(shè)計有所幫助。

        本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
        轉(zhuǎn)藏 分享 獻(xiàn)花(0

        0條評論

        發(fā)表

        請遵守用戶 評論公約

        類似文章 更多