本文的文字及圖片來源于網路,僅供學習、交流使用,不具有任何商業用途,著作權歸原作者所有,如有問題請及時聯系我們以作處理
以下文章來源于Python之王 ,作者小sen
入門
Python內置了很多有用的函式,我們可以直接呼叫,
要呼叫一個函式,需要知道函式的名稱和引數,比如求絕對值的函式abs,只有一個引數,
也可以在互動式命令列通過help(abs)查看abs函式的幫助資訊,
呼叫abs函式:
>>> abs(100)
100
>>> abs(-20)
20
>>> abs(12.34)
12.34
函式式編程
在Python中的函式就是為了實作某一段功能的代碼段,可以重復利用,
就是以后不要重復造輪子,遇到那個場景就用那個函式,就是函式式編程,
下面,我定義一個 my_func,傳入一個Hello World,再列印一個Hello World
def my_func(message):
print('Got a message: {}'.format(message))
# 呼叫函式 my_func()
my_func('Hello World')
# 輸出
Got a message: Hello World
簡單的知識點
- def是函式的宣告
- my_func是函式的名稱
- message 是函式的引數
- print 是函式的主體部分
- 在函式的最后 可以回傳呼叫結果(return 或yield ),也可以不回傳
「定義在前,呼叫在后」
def my_sum(a, b):
return a + b
result = my_sum(3, 5)
print(result)
# 輸出
8
對于函式的引數可以設定默認值
def func(param = 0):
pass
如果param沒有傳入,那么引數默認是0,如果傳入了引數,就覆寫默認值
多型
傳入的引數可以接受任何資料型別
比如,串列
print(my_sum([1, 2], [3, 4]))
# 輸出
[1, 2, 3, 4]
再比如,字串
print(my_sum('hello ', 'world'))
# 輸出
hello world
當然,如果引數資料型別不同,而兩者無法相加
print(my_sum([1, 2], 'hello'))
TypeError: can only concatenate list (not "str") to list
同一個函式可以應用到整數,串列,字串等等的操作稱為多型,這可不是變態,
嵌套函式
函式嵌套就是函式中有函式,就叫嵌套函式了,
def f1():
print('hello')
def f2():
print('world')
f2()
f1()
# 輸出
hello
world
函式的嵌套保證了內部函式的呼叫,內部函式只能被外部函式所呼叫,不會作用于全域域中,
合理使用函式嵌套,提高運算速度
比如計算5的階乘,
def factorial(input):
if not isinstance(input, int):
raise Exception('input must be an integer.')
if input < 0:
raise Exception('input must be greater or equal to 0' )
def inner_factorial(input):
if input <= 1:
return 1
return input * inner_factorial(input-1)
return inner_factorial(input)
print(factorial(5))
120
函式變數作用域
如果變數是izai函式內部定義的,稱為區域變數,只在函式內部有效,當函式執行完畢,區域變數就會被回收,
全域變數就是寫在函式外面的,
MIN_VALUE = 1
MAX_VALUE = 10
def validation_check(value):
if value < MIN_VALUE or value > MAX_VALUE:
raise Exception('validation check fails')
這里的MIN_VELUE 和MAX_VALUE就是全域變數,但是我們不能在函式的內部隨意改變全域變數的值
MIN_VALUE = 1
def validation_check(value):
MIN_VALUE += 1
validation_check(5)
報錯:UnboundLocalError: local variable 'MIN_VALUE' referenced before assignment
要想改變 必須加上global這個宣告
MIN_VALUE = 1
def validation_check(value):
global MIN_VALUE
MIN_VALUE += 1
validation_check(5)
global告訴python決議器,函式內部的變數MIN_VALUE就是定義的全域變數,這里輸入的是2,這樣修改的全域變數的值
MIN_VALUE = 1
MAX_VALUE = 10
def validation_check():
MIN_VALUE = 3
print(MIN_VALUE)
validation_check()
print(MIN_VALUE)
# 3
# 1
對于嵌套函式來說,內部函式無法修改外部函式定義的變數,可以訪問,想要修改就要加上 nonolocal
def outer():
x = "local"
def inner():
nonlocal x # nonlocal 關鍵字表示這里的 x 就是外部函式 outer 定義的變數 x
x = 'nonlocal'
print("inner:", x)
inner()
print("outer:", x)
outer()
# 輸出
inner: nonlocal
outer: nonlocal
不加就不會覆寫
def outer():
x = "local"
def inner():
x = 'nonlocal' # 這里的 x 是 inner 這個函式的區域變數
print("inner:", x)
inner()
print("outer:", x)
outer()
# 輸出
inner: nonlocal
outer: local
閉包
函式的閉包其實和函式的嵌套很相似,和嵌套不同,閉包的外部函式回傳是一個函式,而不是一個具體的值,
閉包就是在函式里面呼叫函式,一般用return來執行,return出內部呼叫的函式名,
我們接下來計算下一個數的n次冪,用閉包寫如下:
def nth_power(exponent):
def exponent_of(base):
return base ** exponent
return exponent_of # 回傳值是 exponent_of 函式
square = nth_power(2) # 計算一個數的平方
cube = nth_power(3) # 計算一個數的立方
square
# 輸出
<function __main__.nth_power.<locals>.exponent(base)>
cube
# 輸出
<function __main__.nth_power.<locals>.exponent(base)>
print(square(2)) # 計算 2 的平方
print(cube(2)) # 計算 2 的立方
# 輸出
4 # 2^2
8 # 2^3
當然,我們也可以通過一個函式來寫這個功能:
def nth_power(base,exponent):
return base**exponent
但是,使用閉包,可以讓程式變得更加簡潔易懂,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/182737.html
標籤:Python
