Python菜鸟之路:Python基础——函数
一、函數
1. 簡介
函數是組織好的,可重復使用的,用來實現單一,或相關聯功能的代碼段。函數能提高應用的模塊性,和代碼的重復利用率。
2. 組成
函數代碼塊以def關鍵詞開頭,后接函數名和圓括號()。
任何傳入參數和自變量必須放在圓括號中間。圓括號之間可以用于定義參數。
函數的第一行語句可以選擇性地使用文檔字符串—用于存放函數說明。
函數主體部分:函數內容以冒號起始,并且縮進。
函數結束部分:return [表達式]結束函數,選擇性地返回一個值給調用方。不帶表達式的return相當于返回 None。
示例:
1 def functionname( parameters ): 2 "函數聲明、注釋等內容,一般為__doc__部分" 3 函數主體部分 4 return [expression]
3. 簡單調用
以上邊的示例為例,調用方法很簡單執行如下代碼。
functionname(參數)
注意,函數定義好之后,并不會運行。只有在調用的時候會運行。
二、函數各組成部分
2.1 函數的命名
函數名應該為小寫,可以用下劃線風格單詞以增加可讀性。如:myfunction,my_example_function。
Python之父Guido推薦的命名規范包括如下幾點:模塊名和包名采用小寫字母并且以下劃線分隔單詞的形式;
類名采用以大寫字母開頭,并且以大寫字母分隔單詞的形式命名;
全局或者類常量,全部使用大寫字母,并且以下劃線分隔單詞;其余變量命名則是采用全部小寫字母,并且以下劃線分隔單詞的形式命名。
以上的內容如果是內部的,則使用下劃線開頭命名。
2.2 函數參數
函數的參數分為三類:普通參數、默認參數、指定參數、可變參數
2.2.1 普通參數
1 def functionname(name,age):
2 print("I'm %s, age %s" % (name, age))
3
4 functionname("wzg",18)
5 out: I'm wzg, age 18
2.2.2 默認參數
1 def functionname(name,age=18):
2 print("I'm %s, age %s" % (name, age))
3
4 functionname("wzg")
5 out: I'm wzg, age 18
2.2.3 指定參數
1 def functionname(name,age=18):
2 print("I'm %s, age %s" % (name, age))
3
4 functionname(age=18, name="wzg")
5 out: I'm wzg, age 18
2.2.4 可變參數
2.2.4.1 可變參數*
1 def function_name(*args): 2 print(args, type(args)) 3 4 function_name(1,2,3) 5 out: (1, 2, 3) <class 'tuple'> 6 7 function_name((1,2,3)) 8 out: ((1, 2, 3),) <class 'tuple'>
由上邊的例子可以看出,默認將傳入的參數,全部放在元組中,即args = (...),在執行()的時候,會進行tuple.__init__方法。
1 def function_name(*args):
2 print(args, type(args))
3 function_name(*(1,2,3))
4
5 out: (1, 2, 3) <class 'tuple'>
6
7 function_name(*'wzg')
8
9 out: ('w', 'z', 'g') <class 'tuple'>
從上邊的例子,可以看出帶*的參數,會循環變量中的每個元素加入至tuple中。字符串的話循環每個字母。
2.2.4.2 可變參數**
1 def function_name(**args):
2 print(args, type(args))
3 function_name(name='wzg')
4 out: {'name': 'wzg'} <class 'dict'>
5 dic={"k1":"v1","k2":"v2"}
6 function_name(**dic)
7 out: {'k1': 'v1', 'k2': 'v2'} <class 'dict'>
8 function_name(d1=dic)
9 out: {'d1': {'k1': 'v1', 'k2': 'v2'}} <class 'dict'>
從上邊的例子可以看出,可變參數** , 默認將參數的參數,全部放在字典中進行處理。
2.3 函數注釋
Python有一種獨一無二的的注釋方式: 使用文檔字符串. 文檔字符串是包, 模塊, 類或函數里的第一個語句. 這些字符串可以通過對象的__doc__成員被自動提取, 并且被pydoc所用。參照下面的一個代碼
1 def function_name(big_table, keys, other_silly_variable=None):
2 """Fetches rows from a Bigtable.
3
4 Retrieves rows pertaining to the given keys from the Table instance
5 represented by big_table. Silly things may happen if
6 other_silly_variable is not None.
7
8 Args:
9 big_table: An open Bigtable Table instance.
10 keys: A sequence of strings representing the key of each table row
11 to fetch.
12 other_silly_variable: Another optional variable, that has a much
13 longer name than the other args, and which does nothing.
14
15 Returns:
16 A dict mapping keys to the corresponding table row data
17 fetched. Each row is represented as a tuple of strings. For
18 example:
19
20 {'Serak': ('Rigel VII', 'Preparer'),
21 'Zim': ('Irk', 'Invader'),
22 'Lrrr': ('Omicron Persei 8', 'Emperor')}
23
24 If a key from the keys argument is missing from the dictionary,
25 then that row was not found in the table.
26
27 Raises:
28 IOError: An error occurred accessing the bigtable.Table object.
29 """
30 function_body
31 return [expression]
注釋
從例子中,可以看出函數注釋包含以下幾個部分:
1.整體功能說明 2.輸入參數說明 3.輸出/返回值說明 4.異常說明 5.其他
2.4 函數主體
函數主體部分就是代碼邏輯的實現/處理過程。
2.5 函數返回值
函數返回值是一個可選的選項,可以返回一個表達式、某種數據結構等。默認返回None
三、函數的分類
函數大概可以分為以下幾類
內建函數
自定義函數
匿名函數
3.1 內建函數__builtins__
從Python3.5官網拔下來一張最新的內置函數列表
與2.7Python相比:
新增:ascii() ,bytes() ,exec(),
減少:basestring() ,cmp(), execfile(), file(),long(),raw_input(),reduce(), reload() , unichr(), unicode() ,xrange()
3.2 常用內建函數
| 函數名 | 作用 |
| all(iterable) | 1、集合中的元素都為真的時候為真 2、特別的,若為空串返回為True |
| any(iterable) | 1、集合中的元素有一個為真的時候為真 2、特別的,若為空串返回為False |
| bool([x]) | 將x轉換為Boolean類型 |
| ascii() | 只要執行這個方法,則會自動調用對象的__repr__。這個函數跟repr()函數一樣,返回一個可打印的對象字符串方式表示。當遇到非ASCII碼時,就會輸出x,u或U等字符來表示。與Python 2版本里的repr()是等效的函數。 |
| abs(x) | 求絕對值 |
| pow(x, y[, z]) | 返回x的y次冪 |
| oct(x) | 將一個數字轉化為8進制 |
| hex(x) | 將整數x轉換為16進制字符串 |
| bin(x) | 將整數x轉換為二進制字符串 |
| bytes("要轉化的字符串", encoding="編碼") | 字符串轉換為字節類型 |
3.3 自定義函數
我們平時使用的大多數函數,以及開發中創建的函數,都屬于自定義函數。這極大的提高了代碼的重用性和可讀性。
自定義函數的創建和使用,在上文中已經進行了說明和示例,參照上邊文章即可。這里不作過多說明。
3.4 匿名函數
python 使用 lambda 來創建匿名函數。
lambda只是一個表達式,函數體比def簡單很多。
lambda的主體是一個表達式,而不是一個代碼塊。僅僅能在lambda表達式中封裝有限的邏輯進去。
lambda函數擁有自己的命名空間,且不能訪問自有參數列表之外或全局命名空間里的參數。
雖然lambda函數看起來只能寫一行,卻不等同于C或C++的內聯函數,后者的目的是調用小函數時不占用棧內存從而增加運行效率。
3.4.1 匿名函數創建語法
lambda [arg1 [,arg2,.....argn]]:expression
3.4.2 示例
>>> lambda x: x+1 #一個參數
>>> lambda x,y,z:x+y+z #多個參數
>>> lambda x,y=3: x*y #允許參數存在默認值,但是默認值的參數必須參數順序最后
1 a= lambda x,y=3: x*y 2 print(a(4)) 3 4 out: 12 5 6 print(a(2,4)) 7 8 out: 8 9 10 b= lambda x,y,z: x*y*z 11 print(b(1,2,3)) 12 13 out: 6
lambda
四、作用域
python中的作用域分4種情況:
L:local,局部作用域,即函數中定義的變量;
E:enclosing,嵌套的父級函數的局部作用域,即包含此函數的上級函數的局部作用域,但不是全局的;
G:global,全局變量,就是模塊級別定義的變量;
B:built-in,系統固定模塊里面的變量,比如int, bytearray等。
搜索變量的優先級順序依次是:作用域局部>外層作用域>當前模塊中的全局>python內置作用域,也就是LEGB。
Python中,是以函數作為作用域的,沒有塊級作用域的概念,這點同js一樣。這里的塊級是只if.while,for等語句。要深入理解Python作用域,有以下幾個要點:
Python中存在作用域鏈,查找順序為由內到外,直到查不到時報錯not defined
Python的作用域,在函數沒有執行之前就已經全部確定,作用域鏈也已經確定
Python函數在沒有執行之前,函數內部不執行。而部分作用域的情況,是需要去看到底有沒有執行。
具體代碼如下:
name = 'boss'
def f1():
print(name)
def f2():
name = 'eric'
return f1
ret = f2()
ret()
# out: boss
#-------------------------
name = 'boss'
def f1():
print(name)
def f2():
name = 'eric'
f1()
f2()
# out: boss
作用域鏈案例
li = []
for i in range(10):
def f1():
return i
li.append(f1)
print(li[0]()) # out: 9
print(li[1]()) # out: 9
print(li[2]()) # out: 9
print(li[3]()) # out: 9
#--------------------------------本質去看有沒有執行
li = []
for i in range(10):
def f1(x=i):
return x
li.append(f1)
print(li[0]()) # out: 0
print(li[1]()) # out: 1
print(li[2]()) # out: 2
print(li[3]()) # out: 3
函數在沒執行之前,內部不執行案例1
1 li =[lambda :x for x in range(10)] 2 3 ret = li[0]() 4 print(ret) # out: 9 5 ret = li[1]() 6 print(ret) # out: 9 7 ret = li[2]() 8 print(ret) # out: 9
函數在沒執行之前,內部不執行案例2
五、文件操作
操作文件,一般需要經過三大步驟
1. 打開文件
2. 操作文件
3. 關閉文件(非必須)
3.1打開文件
打開文件時,需要指定文件路徑和以何等方式打開文件,打開后,即可獲取該文件句柄,日后通過此文件句柄對該文件操作。通常我們使用open()函數來打開文件,源碼中說明了打開模式:
1 def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): # known special case of open
2 """
3 Open file and return a stream. Raise IOError upon failure.
4
5 file is either a text or byte string giving the name (and the path
6 if the file isn't in the current working directory) of the file to
7 be opened or an integer file descriptor of the file to be
8 wrapped. (If a file descriptor is given, it is closed when the
9 returned I/O object is closed, unless closefd is set to False.)
10
11 mode is an optional string that specifies the mode in which the file
12 is opened. It defaults to 'r' which means open for reading in text
13 mode. Other common values are 'w' for writing (truncating the file if
14 it already exists), 'x' for creating and writing to a new file, and
15 'a' for appending (which on some Unix systems, means that all writes
16 append to the end of the file regardless of the current seek position).
17 In text mode, if encoding is not specified the encoding used is platform
18 dependent: locale.getpreferredencoding(False) is called to get the
19 current locale encoding. (For reading and writing raw bytes use binary
20 mode and leave encoding unspecified.) The available modes are:
21
22 ========= ===============================================================
23 Character Meaning
24 --------- ---------------------------------------------------------------
25 'r' open for reading (default)
26 'w' open for writing, truncating the file first
27 'x' create a new file and open it for writing 如果文件存在則報錯
28 'a' open for writing, appending to the end of the file if it exists
29 'b' binary mode
30 't' text mode (default)
31 '+' open a disk file for updating (reading and writing)
32 'U' universal newline mode (deprecated)
33 ========= ===============================================================
34
35 The default mode is 'rt' (open for reading text). For binary random
36 access, the mode 'w+b' opens and truncates the file to 0 bytes, while
37 'r+b' opens the file without truncation. The 'x' mode implies 'w' and
38 raises an `FileExistsError` if the file already exists.
39
40 Python distinguishes between files opened in binary and text modes,
41 even when the underlying operating system doesn't. Files opened in
42 binary mode (appending 'b' to the mode argument) return contents as
43 bytes objects without any decoding. In text mode (the default, or when
44 't' is appended to the mode argument), the contents of the file are
45 returned as strings, the bytes having been first decoded using a
46 platform-dependent encoding or using the specified encoding if given.
47
48 'U' mode is deprecated and will raise an exception in future versions
49 of Python. It has no effect in Python 3. Use newline to control
50 universal newlines mode.
51
52 buffering is an optional integer used to set the buffering policy.
53 Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
54 line buffering (only usable in text mode), and an integer > 1 to indicate
55 the size of a fixed-size chunk buffer. When no buffering argument is
56 given, the default buffering policy works as follows:
57
58 * Binary files are buffered in fixed-size chunks; the size of the buffer
59 is chosen using a heuristic trying to determine the underlying device's
60 "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
61 On many systems, the buffer will typically be 4096 or 8192 bytes long.
62
63 * "Interactive" text files (files for which isatty() returns True)
64 use line buffering. Other text files use the policy described above
65 for binary files.
66
67 encoding is the name of the encoding used to decode or encode the
68 file. This should only be used in text mode. The default encoding is
69 platform dependent, but any encoding supported by Python can be
70 passed. See the codecs module for the list of supported encodings.
71
72 errors is an optional string that specifies how encoding errors are to
73 be handled---this argument should not be used in binary mode. Pass
74 'strict' to raise a ValueError exception if there is an encoding error
75 (the default of None has the same effect), or pass 'ignore' to ignore
76 errors. (Note that ignoring encoding errors can lead to data loss.)
77 See the documentation for codecs.register or run 'help(codecs.Codec)'
78 for a list of the permitted encoding error strings.
79
80 newline controls how universal newlines works (it only applies to text
81 mode). It can be None, '', '
', '', and '
'. It works as
82 follows:
83
84 * On input, if newline is None, universal newlines mode is
85 enabled. Lines in the input can end in '
', '', or '
', and
86 these are translated into '
' before being returned to the
87 caller. If it is '', universal newline mode is enabled, but line
88 endings are returned to the caller untranslated. If it has any of
89 the other legal values, input lines are only terminated by the given
90 string, and the line ending is returned to the caller untranslated.
91
92 * On output, if newline is None, any '
' characters written are
93 translated to the system default line separator, os.linesep. If
94 newline is '' or '
', no translation takes place. If newline is any
95 of the other legal values, any '
' characters written are translated
96 to the given string.
97
98 If closefd is False, the underlying file descriptor will be kept open
99 when the file is closed. This does not work when a file name is given
100 and must be True in that case.
101
102 A custom opener can be used by passing a callable as *opener*. The
103 underlying file descriptor for the file object is then obtained by
104 calling *opener* with (*file*, *flags*). *opener* must return an open
105 file descriptor (passing os.open as *opener* results in functionality
106 similar to passing None).
107
108 open() returns a file object whose type depends on the mode, and
109 through which the standard file operations such as reading and writing
110 are performed. When open() is used to open a file in a text mode ('w',
111 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
112 a file in a binary mode, the returned class varies: in read binary
113 mode, it returns a BufferedReader; in write binary and append binary
114 modes, it returns a BufferedWriter, and in read/write mode, it returns
115 a BufferedRandom.
116
117 It is also possible to use a string or bytearray as a file for both
118 reading and writing. For strings StringIO can be used like a file
119 opened in a text mode, and for bytes a BytesIO can be used like a file
120 opened in a binary mode.
121 """
122 pass
open函數3.5.1源碼
| 模式 | 描述 |
|---|---|
| r | 以只讀方式打開文件。文件的指針將會放在文件的開頭。這是默認模式。 |
| rb | 以二進制格式打開一個文件用于只讀。文件指針將會放在文件的開頭。這是默認模式。 |
| r+ | 打開一個文件用于讀寫。文件指針將會放在文件的開頭。 |
| rb+ | 以二進制格式打開一個文件用于讀寫。文件指針將會放在文件的開頭。 |
| w | 打開一個文件只用于寫入。如果該文件已存在則將其覆蓋。如果該文件不存在,創建新文件。 |
| wb | 以二進制格式打開一個文件只用于寫入。如果該文件已存在則將其覆蓋。如果該文件不存在,創建新文件。 |
| w+ | 打開一個文件用于讀寫。如果該文件已存在則將其覆蓋。如果該文件不存在,創建新文件。這種方法基本不用 |
| wb+ | 以二進制格式打開一個文件用于讀寫。如果該文件已存在則將其覆蓋。如果該文件不存在,創建新文件。 |
| a | 打開一個文件用于追加。如果該文件已存在,文件指針將會放在文件的結尾。也就是說,新的內容將會被寫入到已有內容之后。如果該文件不存在,創建新文件進行寫入。 |
| ab | 以二進制格式打開一個文件用于追加。如果該文件已存在,文件指針將會放在文件的結尾。也就是說,新的內容將會被寫入到已有內容之后。如果該文件不存在,創建新文件進行寫入。 |
| a+ | 打開一個文件用于讀寫。如果該文件已存在,文件指針將會放在文件的結尾。文件打開時會是追加模式。如果該文件不存在,創建新文件用于讀寫。 |
| ab+ |
以二進制格式打開一個文件用于追加。如果該文件已存在,文件指針將會放在文件的結尾。如果該文件不存在,創建新文件用于讀寫。 |
| x |
如果文件存在則報錯,如果不存在,則創建文件并寫內容 |
3.2 操作文件
創建文件句柄之后,可以針對句柄對文件進行如下操縱
1 class TextIOWrapper(_TextIOBase): 2 """ 3 Character and line based layer over a BufferedIOBase object, buffer. 4 5 encoding gives the name of the encoding that the stream will be 6 decoded or encoded with. It defaults to locale.getpreferredencoding(False). 7 8 errors determines the strictness of encoding and decoding (see 9 help(codecs.Codec) or the documentation for codecs.register) and 10 defaults to "strict". 11 12 newline controls how line endings are handled. It can be None, '', 13 ' ', '', and ' '. It works as follows: 14 15 * On input, if newline is None, universal newlines mode is 16 enabled. Lines in the input can end in ' ', '', or ' ', and 17 these are translated into ' ' before being returned to the 18 caller. If it is '', universal newline mode is enabled, but line 19 endings are returned to the caller untranslated. If it has any of 20 the other legal values, input lines are only terminated by the given 21 string, and the line ending is returned to the caller untranslated. 22 23 * On output, if newline is None, any ' ' characters written are 24 translated to the system default line separator, os.linesep. If 25 newline is '' or ' ', no translation takes place. If newline is any 26 of the other legal values, any ' ' characters written are translated 27 to the given string. 28 29 If line_buffering is True, a call to flush is implied when a call to 30 write contains a newline character. 31 """ 32 def close(self, *args, **kwargs): # real signature unknown 33 pass '''關閉文件句柄''' 34 35 def detach(self, *args, **kwargs): # real signature unknown 36 pass '''移除掉已存在的文本編碼層''' 37 38 def fileno(self, *args, **kwargs): # real signature unknown 39 pass '''返回所使用的底層實現請求從操作系統I/O操作的整數文件描述符''' 40 41 def flush(self, *args, **kwargs): # real signature unknown 42 pass '''將緩沖區數據刷入文件''' 43 44 def isatty(self, *args, **kwargs): # real signature unknown 45 pass '''判斷當前文件是否連入tty設備''' 46 47 def read(self, *args, **kwargs): # real signature unknown 48 pass '''讀取文件中所有內容''' 49 50 def readable(self, *args, **kwargs): # real signature unknown '''判斷文件是否可讀''' 51 pass 52 53 def readline(self, *args, **kwargs): # real signature unknown '''僅讀取文件的一行''' 54 pass 55 56 def seek(self, *args, **kwargs): # real signature unknown 57 pass '''設置文件指針的位置''' 58 59 def seekable(self, *args, **kwargs): # real signature unknown '''判斷文件指針是否可修改''' 60 pass 61 62 def tell(self, *args, **kwargs): # real signature unknown 63 pass '''返回該文件指針的當前位置''' 64 65 def truncate(self, *args, **kwargs): # real signature unknown '''截斷文件當前指針之后的內容,僅保留指針之前的''' 66 pass 67 68 def writable(self, *args, **kwargs): # real signature unknown '''判斷文件是否可寫''' 69 pass 70 71 def write(self, *args, **kwargs): # real signature unknown 72 pass '''將字符串寫入文件''' 73 74 def __getstate__(self, *args, **kwargs): # real signature unknown 75 pass 76 77 def __init__(self, *args, **kwargs): # real signature unknown 78 pass 79 80 @staticmethod # known case of __new__ 81 def __new__(*args, **kwargs): # real signature unknown 82 """ Create and return a new object. See help(type) for accurate signature. """ 83 pass 84 85 def __next__(self, *args, **kwargs): # real signature unknown 86 """ Implement next(self). """ 87 pass 88 89 def __repr__(self, *args, **kwargs): # real signature unknown 90 """ Return repr(self). """ 91 pass 92 93 buffer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 94 95 closed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 96 97 encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 98 99 errors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 100 101 line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 102 103 name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 104 105 newlines = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 106 107 _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 108 109 _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
python3.5.1源碼
3.3 關閉文件
這步操作并不是必須的,如果使用open()函數打開文件,那么要記得最終close()文件
如果使用with 語句打開的文件,則不需要。在with 語句主體語句執行完之后,會自動調用close()來關閉文件句柄。語法如下:
1 with open('db1', 'r', encoding="utf-8") as f1:
2 for line in f1:
3 print(line)
同時打開2個文件,語法如下:
1 with open('file1', 'r', encoding="utf-8") as f1, open("file2", 'w',encoding="utf-8") as f2:
2 pass
本章總結至此結束!
總結
以上是生活随笔為你收集整理的Python菜鸟之路:Python基础——函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 校招基础——同步和异步
- 下一篇: vue中8种组件传参方式