Python3學習(2)-中級篇


 


 

  • 切片:取數組、元組中的部分元素
    •  L=['Jack','Mick','Leon','Jane','Aiden']
    • 取前三個:使用索引
    • 取2-4個元素:索引
    • 取最后2個元素:索引,倒序
    • 取前3個元素:索引
  • N=[0,1,2,3,4,5,6,7,8,9]
    • 前8個中每2個取1個
    • 每3個中取1個
  • 高階函數:map/reduce/filter/sorted
    • map:map()函數接收兩個參數,一個是函數,一個是Iterablemap將傳入的函數依次作用到序列的每個元素,並把結果作為新的Iterator返回。
      • >>> def f(x):
        ...     return x*x
        ...
        >>> r = map(f,[0,1,2,3,4,5,6,7,8,9])
        >>> list(r)
        [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    • reduce:reduce把一個函數作用在一個序列[x1, x2, x3, ...]上,這個函數必須接收兩個參數,reduce把結果繼續和序列的下一個元素做累積計算
    • >>> from functools import reduce
      >>> def add(x,y):
      ...     return x+y
      ...
      >>> reduce(add,[1,3,5,7,9])
      25
    • filter:filter()把傳入的函數依次作用於每個元素,然后根據返回值是True還是False決定保留還是丟棄該元素。
    • >>> def is_odd(n):
      ...     return n % 2 == 1
      ...
      >>> list(filter(is_odd,[1,2,4,5,6,9,10,15]))
      [1, 5, 9, 15]
    • sorted:接收一個key函數來實現自定義的排序,例如按絕對值大小排序
    • >>> sorted([36,5,-12,9,-21],key=abs)    #按abs的結果升序排列
      [5, 9, -12, -21, 36]
      >>> sorted(['BOB','aBOUT','zoo','Credit'])    #按首字母的ASICC碼
      ['BOB', 'Credit', 'aBOUT', 'zoo']
  • 匿名函數
    • 關鍵字lambda表示匿名函數,冒號前面的x表示函數參數
    • 只能有一個表達式,不用寫return,返回值就是該表達式的結果
    • >>> f = lambda x:x*x
      >>> f(5)
      25
  • 面向對象
    • 對象
      • 萬物皆為對象
      • 所有事物均可封裝為對象
    •  1 #定義一個Student的對象
       2 class Student(Object):
       3     #初始化對象的屬性
       4     def __init__(self,name,score):
       5         self.name = name
       6         self.score = score
       7 
       8     #定義一個對象的方法print_score    
       9     def print_score(self):
      10         print('%s: %s'%(self.name,self.score))
    • 訪問限制
      • 屬性前加'__'(雙下划線)表示私有的屬性,僅可內部訪問,外部無法訪問
      •  1 #定義一個Student的對象
         2 class Student(Object):
         3     #初始化對象的屬性
         4     def __init__(self,name,score):
         5         #私有屬性
         6         self.__name = name
         7         self.__score = score
         8 
         9     #定義一個對象的函數print_score    
        10     def print_score(self):
        11         print('%s: %s'%(self.__name,self.__score))
    • 繼承和多態
      • 繼承:兒子會直接繼承父親的屬性
      • 多態:可重寫父類的方法
    •  獲取對象信息
      • type(Object):輸出對象的類型。
        • >>> a='AAA'
          >>> type(a)
          <class 'str'>
      • isinstance(Object,Type):判斷對象的類型
        • >>> isinstance('a',str)
          True
          >>> isinstance(123,int)
          True
          >>> isinstance(123,str)
          False
      •  dir(Object):顯示對象的所有屬性和方法
        • >>> dir('a')
          ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
      • 實例屬性和類方法
        • >>> class Student(object):
          ...     name = 'Student'
          ...
          >>> s = Student()
          >>> print(s.name)
          Student
          >>> print(Student.name)
          Student
          >>> s.name = 'Jack'
          >>> print(s.name)
          Jack
          >>> print(Student.name)
          Student
  • 單元測試
    • 用來對一個模塊、一個函數或者一個類來進行正確性檢驗的測試工作。
    • 被測試模塊mydict.py
      •  1 class Dict(dict):
         2 
         3     def __init__(self,**kw):
         4         super().__init__(**kw)
         5 
         6 
         7     def __getattr__(self,key):
         8         try:
         9             return self[key]
        10         except KeyError:
        11             raise AttributeError(r"'Dict' object has no attribute %s" %key)
        12 
        13     def __setattr__(self,key,value):
        14         self[key] = value
    • 測試模塊TestDict.py
      •  1 import unittest
         2 
         3 from mydict import Dict
         4 
         5 class TestDict(unittest.TestCase):
         6 
         7     def test_init(self):
         8         #完成數據初始化
         9         d = Dict(a=1,b='test')
        10         #判斷d.a是否為1,為1則PASS,否則FAIL
        11         self.assertEqual(d.a,1)
        12         #判斷d.b是否為'test'
        13         self.assertEqual(d.b,'test')
        14         self.assertTrue(isinstance(d,dict))
        15 
        16 
        17 
        18 if __name__ == '__main__':
        19     unittest.main()
    • 執行及結果:僅測試一個方法test_init(),且執行通過
      • ➜  Python  python3 TestDict.py
        .
        ----------------------------------------------------------------------
        Ran 1 test in 0.000s
        
        OK
    • 說明
      • 測試模塊需要繼承unittest.TestCase
      • 測試方法命名需要以test開頭
      • 使用斷言來測試結果
      • setUp():在測試模塊執行前,執行的方法
      • tearDown():在測試模塊執行結束后,執行的方法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM