Python開發【第三篇】:函數&讀寫檔案

來源:互聯網
上載者:User

標籤:rac   技術分享   __new__   body   模式   init   定義   col   written   

三元運算

三元運算,是條件陳述式的簡單的寫法。如果條件為真,則傳回值1,否則,傳回值2。

ret = 值1 if 條件 else 值2
深淺拷貝

對於數字(int)和字串(str)而言,賦值、深拷貝、淺拷貝都無意義,因為記憶體位址指向同一個。

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

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

(1)賦值,只是建立一個變數,該變數指向原來記憶體位址;

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

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

函數

在學習函數之前,寫代碼一直是面向過程編程,即:代碼執行順序從上到下,一段代碼執行所需的功能,頻繁涉及到重複內容。

為了更好的代碼重用性和可讀性,出現了函數和物件導向。

  • 函數式:將某功能代碼封裝到函數中,日後便無需重複編寫,僅調用函數即可
  • 物件導向:對函數進行分類和封裝,讓開發“更快更好更強...”
def 函數名(參數):           ...    函數體    ...    傳回值

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

  • def:表示函數的關鍵字
  • 函數名:函數的名稱,日後根據函數名調用函數
  • 函數體:函數中進行一系列的邏輯計算
  • 參數:為函數體提供資料
  • 傳回值:當函數執行完畢後,可以給調用者返回資料。
內建函數

查看詳細內容:點這裡!

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

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

  • 開啟檔案
  • 操作檔案

 一、開啟檔案:f = open("檔案路徑","開啟模式")

開啟檔案的模式有:

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

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

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

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

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

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

二、操作

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
View Code

三、管理上下文

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

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

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

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

with open(‘log1‘) as obj1, open(‘log2‘) as obj2:
pass
lambda運算式

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

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

# 普通條件陳述式if 1 == 1:    name = ‘wupeiqi‘else:    name = ‘alex‘    # 三元運算name = ‘wupeiqi‘ if 1 == 1 else ‘alex‘# ###################### 普通函數 ####################### 定義函數(普通方式)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)

 

Python開發【第三篇】:函數&讀寫檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.