如果想定義一個什麼事也不做的空函數,可以用pass
語句:
def nop(): pass
pass
語句什麼都不做,那有什麼用?其實pass
可以用來當佔位符,例如現在還沒想好怎麼寫函數的程式碼,就可以先放一個pass
,讓程式碼能運作起來。
pass
也可以用在其他語句裡,例如if
定義函數時,需要確定函數名稱和參數個數;
如果有必要,可以先對參數的資料型別做檢查;
函數體內部可以用return
隨時傳回函數結果;
函數執行完畢也沒有return
語句時,自動return None
。
函數可以同時回傳多個值,但其實就是一個tuple。
在Python函數中,也可以定義可變參數。顧名思義,可變參數就是傳入的參數個數是可變的,可以是1個、2個到任一個,還可以是0個。
*nums
表示把nums
這個list的所有元素當作可變參數傳進去。這種寫法相當有用,而且很常見。
可變參數可讓你傳入0個或任一參數,這些可變參數在函數呼叫時會自動組裝為一個tuple。而關鍵字參數允許你傳入0個或任一包含參數名的參數,這些關鍵字參數在函數內部會自動組裝為一個dict。
關鍵字參數有什麼用?它可以擴展函數的功能。例如,在person
函數裡,我們保證能接收到name
和age
這兩個參數,但是,如果呼叫者願意提供更多的參數,我們也能收到。試想你正在做一個用戶註冊的功能,除了用戶名和年齡是必填項外,其他都是可選項,利用關鍵字參數來定義這個函數就能滿足註冊的需求。
和可變參數類似,也可以先組裝出一個dict,然後,把該dict轉換成關鍵字參數傳進去:
>>> extra = {'city': 'Beijing', 'job': 'Engineer'}>>> person('Jack', 24, city=extra['city'], job=extra['job']) name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}
當然,上面複雜的呼叫可以用簡化的寫法:
>>> extra = {'city': 'Beijing', 'job': 'Engineer'}>>> person('Jack', 24, **extra) name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}
**extra
表示把extra
這個dict的所有key -value用關鍵字參數傳入到函數的**kw
參數,kw
將獲得一個dict,注意kw
獲得的dict是extra
的一份拷貝,對kw
的改變不會影響到函數外的extra
。
對於關鍵字參數,函數的呼叫者可以傳入任意不受限制的關鍵字參數。至於到底傳入了哪些,就需要在函數內部透過kw
檢查。
仍以person()
函數為例,我們希望檢查是否有city
和job
參數
如果要限制關鍵字參數的名字,就可以用命名關鍵字參數,例如,只接收city
和job
當關鍵字參數。這種方式定義的函數如下:
def person(name, age, *, city, job): print(name, age, city, job)
和關鍵字參數**kw
不同,命名關鍵字參數需要一個特殊分隔符號*
,*
後面的參數被視為命名關鍵字參數。
呼叫方式如下:
>>> person('Jack', 24, city='Beijing', job='Engineer') Jack 24 Beijing Engineer
如果函數定義中已經有了一個可變參數,後面跟著的命名關鍵字參數就不再需要一個特殊分隔符號*
了:
def person(name, age, *args, city, job): print(name, age, args, city, job)
命名關鍵字參數必須傳入參數名,這和位置參數不同。如果沒有傳入參數名,呼叫會報錯:
>>> person('Jack', 24, 'Beijing', 'Engineer') Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: person() takes 2 positional arguments but 4 were given
在Python中定義函數,可以用必選參數、預設參數、可變參數、關鍵字參數和命名關鍵字參數,這5種參數都可以組合使用。但請注意,參數定義的順序必須是:必選參數、預設參數、可變參數、命名關鍵字參數和關鍵字參數。
例如定義一個函數,包含上述若干種參數:
def f1(a, b, c=0, *args, **kw): print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)def f2(a, b, c=0, *, d, **kw): print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)
在函數呼叫的時候,Python解釋器會自動依照參數位置和參數名稱把對應的參數傳進去。
>>> f1(1, 2) a = 1 b = 2 c = 0 args = () kw = {}>>> f1(1, 2, c=3) a = 1 b = 2 c = 3 args = () kw = {}>>> f1(1, 2, 3, 'a', 'b') a = 1 b = 2 c = 3 args = ('a', 'b') kw = {}>>> f1(1, 2, 3, 'a', 'b', x=99) a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99}>>> f2(1, 2, d=99, ext=None) a = 1 b = 2 c = 0 d = 99 kw = {'ext': None}
最神奇的是透過一個tuple和dict,你也可以呼叫上述函數:
>>> args = (1, 2, 3, 4)>>> kw = {'d': 99, 'x': '#'}>>> f1(*args, **kw) a = 1 b = 2 c = 3 args = (4,) kw = {'d': 99, 'x': '#'}>>> args = (1, 2, 3)>>> kw = {'d': 88, 'x': '#'}>>> f2(*args, **kw) a = 1 b = 2 c = 3 d = 88 kw = {'x': '#'}
所以,對於任意函數,都可以透過類似func(*args, **kw)
的形式呼叫它,無論它的參數是如何定義的。
Python的函數具有非常靈活的參數形態,既可以實現簡單的調用,又可以傳入非常複雜的參數。
預設參數一定要用不可變對象,如果是可變對象,程式運行時會有邏輯錯誤!
要注意定義可變參數和關鍵字參數的語法:
*args
是可变参数,args接收的是一个tuple;
**kw
是关键字参数,kw接收的是一个dict。
以及调用函数时如何传入可变参数和关键字参数的语法:
可变参数既可以直接传入:func(1, 2, 3)
,又可以先组装list或tuple,再通过*args
传入:func(*(1, 2, 3))
;
关键字参数既可以直接传入:func(a=1, b=2)
,又可以先组装dict,再通过**kw
传入:func(**{'a': 1, 'b': 2})
。
使用*args
和**kw
是Python的习惯写法,当然也可以用其他参数名,但最好使用习惯用法。
命名的关键字参数是为了限制调用者可以传入的参数名,同时可以提供默认值。
定义命名的关键字参数在没有可变参数的情况下不要忘了写分隔符*
,否则定义的将是位置参数。
注:查看详细猛击这里
文件操作函数
open函数,该函数用于文件处理
操作文件时,一般需要经历如下步骤:
打开文件
操作文件
一、打开文件
文件句柄
=
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
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. """ passPython 2.x
python 2.0
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) # defaultPython 3.x
python3.0
三、管理上下文
为了避免打开文件后忘记关闭,可以通过管理上下文,即:
with open('log','r') as f: ...
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:
with open('log1') as obj1, open('log2') as obj2: pass
学习条件运算时,对于简单的 if else 语句,可以使用三元运算来表示,即:
# 普通条件语句if 1 == 1: name = 'wupeiqi'else: name = 'alex' # 三元运算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)
lambda存在意义就是对简单函数的简洁表示!
def fact(n): if n==1: return 1 return n * fact(n - 1)
递归函数的优点是定义简单,逻辑清晰。理论上,所有的递归函数都可以写成循环的方式,但循环的逻辑不如递归清晰。
使用递归函数需要注意防止栈溢出。在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出。可以试试fact(1000)
:
>>> fact(1)1 >>> fact(5)120 >>> fact(100)93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 ===> fact(5)===> 5 * fact(4)===> 5 * (4 * fact(3))===> 5 * (4 * (3 * fact(2)))===> 5 * (4 * (3 * (2 * fact(1))))===> 5 * (4 * (3 * (2 * 1)))===> 5 * (4 * (3 * 2))===> 5 * (4 * 6)===> 5 * 24 ===> 120
解决递归调用栈溢出的方法是通过尾递归优化,事实上尾递归和循环的效果是一样的,所以,把循环看成是一种特殊的尾递归函数也是可以的。
尾递归是指,在函数返回的时候,调用自身本身,并且,return语句不能包含表达式。这样,编译器或者解释器就可以把尾递归做优化,使递归本身无论调用多少次,都只占用一个栈帧,不会出现栈溢出的情况。
上面的fact(n)
函数由于return n * fact(n - 1)
引入了乘法表达式,所以就不是尾递归了。要改成尾递归方式,需要多一点代码,主要是要把每一步的乘积传入到递归函数中:
def fact(n): return fact_iter(n, 1)def fact_iter(num, product): if num == 1: return product return fact_iter(num - 1, num * product)
可以看到,return fact_iter(num - 1, num * product)
仅返回递归函数本身,num - 1
和num * product
在函数调用前就会被计算,不影响函数调用。
fact(5)
对应的fact_iter(5, 1)
的调用如下:
===> fact_iter(5, 1)===> fact_iter(4, 5)===> fact_iter(3, 20)===> fact_iter(2, 60)===> fact_iter(1, 120)===> 120
尾递归调用时,如果做了优化,栈不会增长,因此,无论多少次调用也不会导致栈溢出。
遗憾的是,大多数编程语言没有针对尾递归做优化,Python解释器也没有做优化,所以,即使把上面的fact(n)
函数改成尾递归方式,也会导致栈溢出。
使用递归函数的优点是逻辑简单清晰,缺点是过深的调用会导致栈溢出。
针对尾递归优化的语言可以通过尾递归防止栈溢出。尾递归事实上和循环是等价的,没有循环语句的编程语言只能通过尾递归实现循环。
Python标准的解释器没有针对尾递归做优化,任何递归函数都存在栈溢出的问题。
#!/usr/bin/env python3# -*- coding: utf-8 -*-# 利用递归函数计算阶乘# N! = 1 * 2 * 3 * ... * Ndef fact(n): if n == 1: return 1 return n * fact(n-1)print('fact(1) =', fact(1))print('fact(5) =', fact(5))print('fact(10) =', fact(10))# 利用递归函数移动汉诺塔:def move(n, a, b, c): if n == 1: print('move', a, '-->', c) return move(n-1, a, c, b) print('move', a, '-->', c) move(n-1, b, a, c) move(4, 'A', 'B', 'C')
以上是python函數用法總結的詳細內容。更多資訊請關注PHP中文網其他相關文章!