python s12 day3

python s12 day3

 

深淺拷貝

對於 數字 和 字符串 而言,賦值、淺拷貝和深拷貝無心義,由於其永遠指向同一個內存地址。html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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))

 

 

對於字典、元祖、列表 而言,進行賦值、淺拷貝和深拷貝時,其內存地址的變化是不一樣的。python

賦值,只是建立一個變量,該變量指向原來內存地址,如:linux

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

淺拷貝,在內存中只額外建立第一層數據編程

1
2
3
4
5
import  copy
 
n1  =  { "k1" "wu" "k2" 123 "k3" : [ "alex" 456 ]}
 
n3  =  copy.copy(n1)

深拷貝,在內存中將全部的數據從新建立一份(排除最後一層,即:python內部對字符串和數字的優化)windows

1
2
3
4
5
import  copy
 
n1  =  { "k1" "wu" "k2" 123 "k3" : [ "alex" 456 ]}
 
n4  =  copy.deepcopy(n1)

函數

1、背景服務器

在學習函數以前,一直遵循:面向過程編程,即:根據業務邏輯從上到下實現功能,其每每用一長段代碼來實現指定功能,開發過程當中最多見的操做就是粘貼複製,也就是將以前實現的代碼塊複製到現需功能處,以下:app

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
while  True
     if  cpu利用率 >  90 % :
         #發送郵件提醒
         鏈接郵箱服務器
         發送郵件
         關閉鏈接
   
     if  硬盤使用空間 >  90 % :
         #發送郵件提醒
         鏈接郵箱服務器
         發送郵件
         關閉鏈接
   
     if  內存佔用 >  80 % :
         #發送郵件提醒
         鏈接郵箱服務器
         發送郵件
         關閉鏈接

腚眼一看上述代碼,if條件語句下的內容能夠被提取出來公用,以下:less

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def  發送郵件(內容)
     #發送郵件提醒
     鏈接郵箱服務器
     發送郵件
     關閉鏈接
   
while  True
   
     if  cpu利用率 >  90 % :
         發送郵件( 'CPU報警' )
   
     if  硬盤使用空間 >  90 % :
         發送郵件( '硬盤報警' )
   
     if  內存佔用 >  80 % :

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

  • 函數式:將某功能代碼封裝到函數中,往後便無需重複編寫,僅調用函數便可
  • 面向對象:對函數進行分類和封裝,讓開發「更快更好更強...」

函數式編程最重要的是加強代碼的重用性和可讀性函數式編程

2、定義和使用

1
2
3
4
5
def  函數名(參數):
      
     ...
     函數體
     ...

函數的定義主要有以下要點:

  • def:表示函數的關鍵字
  • 函數名:函數的名稱,往後根據函數名調用函數
  • 函數體:函數中進行一系列的邏輯計算,如:發送郵件、計算出 [11,22,38,888,2]中的最大數等...
  • 參數:爲函數體提供數據
  • 返回值:當函數執行完畢後,能夠給調用者返回數據。

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

一、返回值

函數是一個功能塊,該功能到底執行成功與否,須要經過返回值來告知調用者。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def  發送短信():
      
     發送短信的代碼...
  
     if  發送成功:
         return  True
     else :
         return  False
  
  
while  True :
      
     # 每次執行發送短信函數,都會將返回值自動賦值給result
     # 以後,能夠根據result來寫日誌,或重發等操做
  
     result  =  發送短信()
     if  result  = =  False :
         記錄日誌,短信發送失敗...

二、參數

爲何要有參數?

複製代碼
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(name, age = 18):
    
    print "%s:%s" %(name,age)

# 指定參數
func('wupeiqi', 19)
# 使用默認參數
func('alex')

注:默認參數須要放在參數列表最後
複製代碼
複製代碼
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(*args, **kwargs):

    print args
    print kwargs

擴展:發送郵件實例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import  smtplib
from  email.mime.text  import  MIMEText
from  email.utils  import  formataddr
  
  
msg  =  MIMEText( '郵件內容' 'plain' 'utf-8' )
msg[ 'From' =  formataddr([ "武沛齊" , 'wptawy@126.com' ])
msg[ 'To' =  formataddr([ "走人" , '424662508@qq.com' ])
msg[ 'Subject' =  "主題"
  
server  =  smtplib.SMTP( "smtp.126.com" 25 )
server.login( "wptawy@126.com" "郵箱密碼" )
server.sendmail( 'wptawy@126.com' , [ '424662508@qq.com' ,], msg.as_string())
server.quit()

內置函數

  

注:查看詳細猛擊這裏

open函數,該函數用於文件處理

操做文件時,通常須要經歷以下步驟:

  • 打開文件
  • 操做文件

1、打開文件

1
文件句柄  =  open ( '文件路徑' '模式' )

打開文件時,須要指定文件路徑和以何等方式打開文件,打開後,便可獲取該文件句柄,往後經過此文件句柄對該文件操做。

打開文件的模式有:

  • r,只讀模式(默認)。
  • w,只寫模式。【不可讀;不存在則建立;存在則刪除內容;】
  • a,追加模式。【可讀;   不存在則建立;存在則只追加內容;】

"+" 表示能夠同時讀寫某個文件

  • r+,可讀寫文件。【可讀;可寫;可追加】
  • w+,寫讀
  • a+,同a

"U"表示在讀取時,能夠將 \r \n \r\n自動轉換成 \n (與 r 或 r+ 模式同使用)

  • rU
  • r+U

"b"表示處理二進制文件(如:FTP發送上傳ISO鏡像文件,linux可忽略,windows處理二進制文件時需標註)

  • rb
  • wb
  • ab

2、操做

複製代碼
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
複製代碼
複製代碼
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、管理上下文

爲了不打開文件後忘記關閉,能夠經過管理上下文,即:

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

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

在Python 2.7 後,with又支持同時對多個文件的上下文進行管理,即:

1
2
with  open ( 'log1' ) as obj1,  open ( 'log2' ) as obj2:
     pass

lambda表達式

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# ###################### 普通函數 ######################
# 定義函數(普通方式)
def  func(arg):
     return  arg  +  1
   
# 執行函數
result  =  func( 123 )
   
# ###################### lambda ######################
   
# 定義函數(lambda表達式)
my_lambda  =  lambda  arg : arg  +  1
   
# 執行函數
result  =  my_lambda( 123 )

lambda存在乎義就是對簡單函數的簡潔表示

遞歸

利用函數編寫以下數列:

斐波那契數列指的是這樣一個數列 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...

1
2
3
4
5
6
7
8
def  func(arg1,arg2):
     if  arg1  = =  0 :
         print  arg1, arg2
     arg3  =  arg1  +  arg2
     print  arg3
     func(arg2, arg3)
 
func( 0 , 1 )

裝飾器

裝飾器是函數,只不過該函數能夠具備特殊的含義,裝飾器用來裝飾函數或類,使用裝飾器能夠在函數執行前和執行後添加相應操做。

1
2
3
4
5
6
7
8
9
10
def  wrapper(func):
     def  result():
         print  'before'
         func()
         print  'after'
     return  result
  
@wrapper
def  foo():
     print  'foo'
複製代碼
import functools


def wrapper(func):
    @functools.wraps(func)
    def wrapper():
        print 'before'
        func()
        print 'after'
    return wrapper

@wrapper
def foo():
    print 'foo'
複製代碼

詳細猛擊這裏

相關文章
相關標籤/搜索