1. 程式人生 > 實用技巧 >策略模式(Strategy Pattern)

策略模式(Strategy Pattern)

三元運算

三元運算(三目運算),是對簡單的條件語句的縮寫。

# 書寫格式
 
result = 值1 if 條件 else 值2
 
# 如果條件成立,那麼將 “值1” 賦值給result變數,否則,將“值2”賦值給result變數

基本資料型別補充

set

set集合,是一個無序且不重複的元素集合

class set(object):
    """
    set() -> new empty set object
    set(iterable) -> new set object
     
    Build an unordered collection of unique elements.
    
""" def add(self, *args, **kwargs): # real signature unknown """ Add an element to a set,新增元素 This has no effect if the element is already present. """ pass def clear(self, *args, **kwargs): # real signature unknown """ Remove all elements from this set. 清除內容
""" pass def copy(self, *args, **kwargs): # real signature unknown """ Return a shallow copy of a set. 淺拷貝 """ pass def difference(self, *args, **kwargs): # real signature unknown """ Return the difference of two or more sets as a new set. A中存在,B中不存在 (i.e. all elements that are in this set but not the others.)
""" pass def difference_update(self, *args, **kwargs): # real signature unknown """ Remove all elements of another set from this set. 從當前集合中刪除和B中相同的元素""" pass def discard(self, *args, **kwargs): # real signature unknown """ Remove an element from a set if it is a member. If the element is not a member, do nothing. 移除指定元素,不存在不保錯 """ pass def intersection(self, *args, **kwargs): # real signature unknown """ Return the intersection of two sets as a new set. 交集 (i.e. all elements that are in both sets.) """ pass def intersection_update(self, *args, **kwargs): # real signature unknown """ Update a set with the intersection of itself and another. 取交集並更更新到A中 """ pass def isdisjoint(self, *args, **kwargs): # real signature unknown """ Return True if two sets have a null intersection. 如果沒有交集,返回True,否則返回False""" pass def issubset(self, *args, **kwargs): # real signature unknown """ Report whether another set contains this set. 是否是子序列""" pass def issuperset(self, *args, **kwargs): # real signature unknown """ Report whether this set contains another set. 是否是父序列""" pass def pop(self, *args, **kwargs): # real signature unknown """ Remove and return an arbitrary set element. Raises KeyError if the set is empty. 移除元素 """ pass def remove(self, *args, **kwargs): # real signature unknown """ Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError. 移除指定元素,不存在保錯 """ pass def symmetric_difference(self, *args, **kwargs): # real signature unknown """ Return the symmetric difference of two sets as a new set. 對稱差集 (i.e. all elements that are in exactly one of the sets.) """ pass def symmetric_difference_update(self, *args, **kwargs): # real signature unknown """ Update a set with the symmetric difference of itself and another. 對稱差集,並更新到a中 """ pass def union(self, *args, **kwargs): # real signature unknown """ Return the union of sets as a new set. 並集 (i.e. all elements that are in either set.) """ pass def update(self, *args, **kwargs): # real signature unknown """ Update a set with the union of itself and others. 更新 """ pass
Set

練習:尋找差異

# 資料庫中原有
old_dict = {
    "#1":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 },
    "#2":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 }
    "#3":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 }
}
   
# cmdb 新彙報的資料
new_dict = {
    "#1":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 800 },
    "#3":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 }
    "#4":{ 'hostname':c2, 'cpu_count': 2, 'mem_capicity': 80 }
}

深淺拷貝

一、數字和字串

對於 數字 和 字串 而言,賦值、淺拷貝和深拷貝無意義,因為其永遠指向同一個記憶體地址。

import copy
# ######### 數字、字串 #########
n1 = 123
# n1 = "i am alex age 10"
print(id(n1))
# ## 賦值 ##
n2 = n1
print(id(n2))
# ## 淺拷貝 ##
n2 = copy.copy(n1)
print(id(n2))
  
# ## 深拷貝 ##
n3 = copy.deepcopy(n1)
print(id(n3))

二、其他基本資料型別

對於字典、元祖、列表 而言,進行賦值、淺拷貝和深拷貝時,其記憶體地址的變化是不同的。

1、賦值

賦值,只是建立一個變數,該變數指向原來記憶體地址,如:

n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]}
  
n2 = n1

2、淺拷貝

淺拷貝,在記憶體中只額外建立第一層資料

import copy
  
n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]}
  
n3 = copy.copy(n1)

3、深拷貝

深拷貝,在記憶體中將所有的資料重新建立一份(排除最後一層,即:python內部對字串和數字的優化)

import copy
  
n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]}
  
n4 = copy.deepcopy(n1)

函式

一、背景

在學習函式之前,一直遵循:面向過程程式設計,即:根據業務邏輯從上到下實現功能,其往往用一長段程式碼來實現指定功能,開發過程中最常見的操作就是貼上複製,也就是將之前實現的程式碼塊複製到現需功能處,如下:

while True:
    if cpu利用率 > 90%:
        #傳送郵件提醒
        連線郵箱伺服器
        傳送郵件
        關閉連線
    
    if 硬碟使用空間 > 90%:
        #傳送郵件提醒
        連線郵箱伺服器
        傳送郵件
        關閉連線
    
    if 記憶體佔用 > 80%:
        #傳送郵件提醒
        連線郵箱伺服器
        傳送郵件
        關閉連線

看上述程式碼,if條件語句下的內容可以被提取出來公用,如下:

def 傳送郵件(內容)
    #傳送郵件提醒
    連線郵箱伺服器
    傳送郵件
    關閉連線
    
while True:
    
    if cpu利用率 > 90%:
        傳送郵件('CPU報警')
    
    if 硬碟使用空間 > 90%:
        傳送郵件('硬碟報警')
    
    if 記憶體佔用 > 80%:

對於上述的兩種實現方式,第二次必然比第一次的重用性和可讀性要好,其實這就是函數語言程式設計和麵向過程程式設計的區別:

  • 函式式:將某功能程式碼封裝到函式中,日後便無需重複編寫,僅呼叫函式即可
  • 面向物件:對函式進行分類和封裝,讓開發“更快更好更強...”

函數語言程式設計最重要的是增強程式碼的重用性和可讀性

二、定義和使用

def 函式名(引數):
       
    ...
    函式體
    ...
    返回值

函式的定義主要有如下要點:

  • def:表示函式的關鍵字
  • 函式名:函式的名稱,日後根據函式名呼叫函式
  • 函式體:函式中進行一系列的邏輯計算,如:傳送郵件、計算出 [11,22,38,888,2]中的最大數等...
  • 引數:為函式體提供資料
  • 返回值:當函式執行完畢後,可以給呼叫者返回資料。

1、返回值

函式是一個功能塊,該功能到底執行成功與否,需要通過返回值來告知呼叫者。

以上要點中,比較重要有引數和返回值:

def 傳送簡訊():
       
    傳送簡訊的程式碼...
   
    if 傳送成功:
        return True
    else:
        return False
   
   
while True:
       
    # 每次執行傳送簡訊函式,都會將返回值自動賦值給result
    # 之後,可以根據result來寫日誌,或重發等操作
   
    result = 傳送簡訊()
    if result == False:
        記錄日誌,簡訊傳送失敗...

2、引數

為什麼要有引數?

def CPU報警郵件()
    #傳送郵件提醒
    連線郵箱伺服器
    傳送郵件
    關閉連線

def 硬碟報警郵件()
    #傳送郵件提醒
    連線郵箱伺服器
    傳送郵件
    關閉連線

def 記憶體報警郵件()
    #傳送郵件提醒
    連線郵箱伺服器
    傳送郵件
    關閉連線
 
while True:
 
    if cpu利用率 > 90%:
        CPU報警郵件()
 
    if 硬碟使用空間 > 90%:
        硬碟報警郵件()
 
    if 記憶體佔用 > 80%:
        記憶體報警郵件()

無引數實現
無引數實現
def 傳送郵件(郵件內容)

    #傳送郵件提醒
    連線郵箱伺服器
    傳送郵件
    關閉連線

 
while True:
 
    if cpu利用率 > 90%:
        傳送郵件("CPU報警了。")
 
    if 硬碟使用空間 > 90%:
        傳送郵件("硬碟報警了。")
 
    if 記憶體佔用 > 80%:
        傳送郵件("記憶體報警了。")

有引數實現

函式的有三中不同的引數:

  • 普通引數
  • 預設引數
  • 動態引數
    # ######### 定義函式 ######### 
    
    # name 叫做函式func的形式引數,簡稱:形參
    def func(name):
        print name
    
    # ######### 執行函式 ######### 
    #  'wupeiqi' 叫做函式func的實際引數,簡稱:實參
    func('wupeiqi')
    
    普通引數
    普通引數
    def func(*args):
    
        print args
    
    
    # 執行方式一
    func(11,33,4,4454,5)
    
    # 執行方式二
    li = [11,2,2,3,3,4,54]
    func(*li)
    
    動態引數
    動態引數
    def func(**kwargs):
    
        print args
    
    
    # 執行方式一
    func(name='wupeiqi',age=18)
    
    # 執行方式二
    li = {'name':'wupeiqi', age:18, 'gender':'male'}
    func(**li)
    
    動態引數
    動態引數
    def func(**kwargs):
    
        print args
    
    
    # 執行方式一
    func(name='wupeiqi',age=18)
    
    # 執行方式二
    li = {'name':'wupeiqi', age:18, 'gender':'male'}
    func(**li)
    
    動態引數
    動態引數
    def func(*args, **kwargs):
    
        print args
        print kwargs
    動態引數
    def func(name, age = 18):
        
        print "%s:%s" %(name,age)
    
    # 指定引數
    func('wupeiqi', 19)
    # 使用預設引數
    func('alex')
    
    注:預設引數需要放在引數列表最後
    
    預設引數
    預設引數

    內建函式

    注:檢視詳細猛擊這裡

    open函式,該函式用於檔案處理

    操作檔案時,一般需要經歷如下步驟:

    • 開啟檔案
    • 操作檔案

    一、開啟檔案

  • 檔案控制代碼 = open('檔案路徑', '模式')

    開啟檔案時,需要指定檔案路徑和以何等方式開啟檔案,開啟後,即可獲取該檔案控制代碼,日後通過此檔案控制代碼對該檔案操作。

    開啟檔案的模式有:

    • r ,只讀模式【預設】
    • w,只寫模式【不可讀;不存在則建立;存在則清空內容;】
    • x, 只寫模式【不可讀;不存在則建立,存在則報錯】
    • a, 追加模式【可讀; 不存在則建立;存在則只追加內容;】

    "+" 表示可以同時讀寫某個檔案

    • r+, 讀寫【可讀,可寫】
    • w+,寫讀【可讀,可寫】
    • x+ ,寫讀【可讀,可寫】
    • a+, 寫讀【可讀,可寫】

    "b"表示以位元組的方式操作

    • rb 或 r+b
    • wb 或 w+b
    • xb或 w+b
    • ab或 a+b

    注:以b方式開啟時,讀取到的內容是位元組型別,寫入時也需要提供位元組型別

    二、操作

class file(object)
    def close(self): # real signature unknown; restored from __doc__
        關閉檔案
        """
        close() -> None or (perhaps) an integer.  Close the file.
         
        Sets data attribute .closed to True.  A closed file cannot be used for
        further I/O operations.  close() may be called more than once without
        error.  Some kinds of file objects (for example, opened by popen())
        may return an exit status upon closing.
        """
 
    def fileno(self): # real signature unknown; restored from __doc__
        檔案描述符  
         """
        fileno() -> integer "file descriptor".
         
        This is needed for lower-level file interfaces, such os.read().
        """
        return 0    
 
    def flush(self): # real signature unknown; restored from __doc__
        重新整理檔案內部緩衝區
        """ flush() -> None.  Flush the internal I/O buffer. """
        pass
 
 
    def isatty(self): # real signature unknown; restored from __doc__
        判斷檔案是否是同意tty裝置
        """ isatty() -> true or false.  True if the file is connected to a tty device. """
        return False
 
 
    def next(self): # real signature unknown; restored from __doc__
        獲取下一行資料,不存在,則報錯
        """ x.next() -> the next value, or raise StopIteration """
        pass
 
    def read(self, size=None): # real signature unknown; restored from __doc__
        讀取指定位元組資料
        """
        read([size]) -> read at most size bytes, returned as a string.
         
        If the size argument is negative or omitted, read until EOF is reached.
        Notice that when in non-blocking mode, less data than what was requested
        may be returned, even if no size parameter was given.
        """
        pass
 
    def readinto(self): # real signature unknown; restored from __doc__
        讀取到緩衝區,不要用,將被遺棄
        """ readinto() -> Undocumented.  Don't use this; it may go away. """
        pass
 
    def readline(self, size=None): # real signature unknown; restored from __doc__
        僅讀取一行資料
        """
        readline([size]) -> next line from the file, as a string.
         
        Retain newline.  A non-negative size argument limits the maximum
        number of bytes to return (an incomplete line may be returned then).
        Return an empty string at EOF.
        """
        pass
 
    def readlines(self, size=None): # real signature unknown; restored from __doc__
        讀取所有資料,並根據換行儲存值列表
        """
        readlines([size]) -> list of strings, each a line from the file.
         
        Call readline() repeatedly and return a list of the lines so read.
        The optional size argument, if given, is an approximate bound on the
        total number of bytes in the lines returned.
        """
        return []
 
    def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
        指定檔案中指標位置
        """
        seek(offset[, whence]) -> None.  Move to new file position.
         
        Argument offset is a byte count.  Optional argument whence defaults to
(offset from start of file, offset should be >= 0); other values are 1
        (move relative to current position, positive or negative), and 2 (move
        relative to end of file, usually negative, although many platforms allow
        seeking beyond the end of a file).  If the file is opened in text mode,
        only offsets returned by tell() are legal.  Use of other offsets causes
        undefined behavior.
        Note that not all file objects are seekable.
        """
        pass
 
    def tell(self): # real signature unknown; restored from __doc__
        獲取當前指標位置
        """ tell() -> current file position, an integer (may be a long integer). """
        pass
 
    def truncate(self, size=None): # real signature unknown; restored from __doc__
        截斷資料,僅保留指定之前資料
        """
        truncate([size]) -> None.  Truncate the file to at most size bytes.
         
        Size defaults to the current file position, as returned by tell().
        """
        pass
 
    def write(self, p_str): # real signature unknown; restored from __doc__
        寫內容
        """
        write(str) -> None.  Write string str to file.
         
        Note that due to buffering, flush() or close() may be needed before
        the file on disk reflects the data written.
        """
        pass
 
    def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
        將一個字串列表寫入檔案
        """
        writelines(sequence_of_strings) -> None.  Write the strings to the file.
         
        Note that newlines are not added.  The sequence can be any iterable object
        producing strings. This is equivalent to calling write() for each string.
        """
        pass
 
    def xreadlines(self): # real signature unknown; restored from __doc__
        可用於逐行讀取檔案,非全部
        """
        xreadlines() -> returns self.
         
        For backward compatibility. File objects now include the performance
        optimizations previously implemented in the xreadlines module.
        """
        pass

2.x
2.x
class TextIOWrapper(_TextIOBase):
    """
    Character and line based layer over a BufferedIOBase object, buffer.
    
    encoding gives the name of the encoding that the stream will be
    decoded or encoded with. It defaults to locale.getpreferredencoding(False).
    
    errors determines the strictness of encoding and decoding (see
    help(codecs.Codec) or the documentation for codecs.register) and
    defaults to "strict".
    
    newline controls how line endings are handled. It can be None, '',
    '\n', '\r', and '\r\n'.  It works as follows:
    
    * On input, if newline is None, universal newlines mode is
      enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
      these are translated into '\n' before being returned to the
      caller. If it is '', universal newline mode is enabled, but line
      endings are returned to the caller untranslated. If it has any of
      the other legal values, input lines are only terminated by the given
      string, and the line ending is returned to the caller untranslated.
    
    * On output, if newline is None, any '\n' characters written are
      translated to the system default line separator, os.linesep. If
      newline is '' or '\n', no translation takes place. If newline is any
      of the other legal values, any '\n' characters written are translated
      to the given string.
    
    If line_buffering is True, a call to flush is implied when a call to
    write contains a newline character.
    """
    def close(self, *args, **kwargs): # real signature unknown
        關閉檔案
        pass

    def fileno(self, *args, **kwargs): # real signature unknown
        檔案描述符  
        pass

    def flush(self, *args, **kwargs): # real signature unknown
        重新整理檔案內部緩衝區
        pass

    def isatty(self, *args, **kwargs): # real signature unknown
        判斷檔案是否是同意tty裝置
        pass

    def read(self, *args, **kwargs): # real signature unknown
        讀取指定位元組資料
        pass

    def readable(self, *args, **kwargs): # real signature unknown
        是否可讀
        pass

    def readline(self, *args, **kwargs): # real signature unknown
        僅讀取一行資料
        pass

    def seek(self, *args, **kwargs): # real signature unknown
        指定檔案中指標位置
        pass

    def seekable(self, *args, **kwargs): # real signature unknown
        指標是否可操作
        pass

    def tell(self, *args, **kwargs): # real signature unknown
        獲取指標位置
        pass

    def truncate(self, *args, **kwargs): # real signature unknown
        截斷資料,僅保留指定之前資料
        pass

    def writable(self, *args, **kwargs): # real signature unknown
        是否可寫
        pass

    def write(self, *args, **kwargs): # real signature unknown
        寫內容
        pass

    def __getstate__(self, *args, **kwargs): # real signature unknown
        pass

    def __init__(self, *args, **kwargs): # real signature unknown
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __next__(self, *args, **kwargs): # real signature unknown
        """ Implement next(self). """
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    buffer = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    closed = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    encoding = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    errors = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    name = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    newlines = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

3.x
3.x

三、管理上下文

為了避免開啟檔案後忘記關閉,可以通過管理上下文,即:

with open('log','r') as f:
        
    ...

如此方式,當with程式碼塊執行完畢時,內部會自動關閉並釋放檔案資源。

在Python 2.7 及以後,with又支援同時對多個檔案的上下文進行管理,即:

with open('log1') as obj1, open('log2') as obj2:
    pass
lambda表示式

lambda表示式

學習條件運算時,對於簡單的 if else 語句,可以使用三元運算來表示,即:

1 # 普通條件語句
2 if 1 == 1:
3     name = 'wupeiqi'
4 else:
5     name = 'alex'
6     
7 # 三元運算
8 name = 'wupeiqi' if 1 == 1 else 'alex'

對於簡單的函式,也存在一種簡便的表示方式,即:lambda表示式

# ###################### 普通函式 ######################
# 定義函式(普通方式)
def func(arg):
    return arg + 1
    
# 執行函式
result = func(123)
    
# ###################### lambda ######################
    
# 定義函式(lambda表示式)
my_lambda = lambda arg : arg + 1
    
# 執行函式
result = my_lambda(123)

遞迴

利用函式編寫如下數列:

斐波那契數列指的是這樣一個數列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368...

def func(arg1,arg2):
    if arg1 == 0:
        print arg1, arg2
    arg3 = arg1 + arg2
    print arg3
    func(arg2, arg3)
  
func(0,1)

# ###################### 普通函式 ###################### # 定義函式(普通方式) deffunc(arg): returnarg+1 # 執行函式 result=func(123) # ###################### lambda ###################### # 定義函式(lambda表示式) my_lambda=lambdaarg : arg+1 # 執行函式 result=my_lambda(123)