導航:首頁 > 編程語言 > python函數嵌套定義

python函數嵌套定義

發布時間:2022-05-26 17:26:42

『壹』 python語言,沒用過Python也進來看看。。一道作業。題目沒怎麼看懂。。。

parseExp是一個「閉包」。
如果在一個內部函數里,對在外部作用域(但不是在全局作用域)的變數進行引用,那麼內部函數就被認為是閉包(closure)。閉包大致可以理解為定義在函數內部的函數。更詳細的內容你可以自己網路「Python 閉包」。JavaScript也有閉包,可以作為參考。
支持閉包的語言有這樣的特性:
1、函數是一階值(First-class value),即函數可以作為另一個函數的返回值或參數,還可以作為一個變數的值。
2、函數可以嵌套定義,即在一個函數內部可以定義另一個函數。
這樣一來Python里的函數就跟類差不多了。
具體到你這段程序:
tokens對於parseExp來說是閉包變數,對於parse來說是參數,它存活在parse函數的名稱空間和作用域中。
tokens是個list,被傳遞給parse(),parseExp()裡面顯然會用到tokens,parseExp(index)中的index是用來從tokens這個list的提取元素的索引,parseExp(0)就是說從tokens的第一項(index=0)開始處理,返回一個值對(parsedExp, nextIndex)。其中parsedExp是由tokens[index]轉換出來的一個變數,nextIndex是尚未處理的下一個tokens元素的索引。
遞歸調用是在<your code here>裡面的,你發的代碼里是沒有的。
把 # <your code here> 那段代碼補全的話大致是這樣:
def parse(tokens):
def parseExp(index):
if tokens[index].isdigit():
return (Number(float(tokens[index])), index+1)
elif tokens[index].isalnum():
return (Variable(tokens[index]), index + 1)
else:
(leftTree, index1) = parseExp(index+1)
op = tokens[index1]
(rightTree, index2) = parseExp(index1+1)
return (ops[op](leftTree, rightTree), index2+1)
(parsedExp, nextIndex) = parseExp(0)
return parsedExp
這基本上是個 expression calculator 。
你應該有個tokenizer.py之類的文件吧?我翻了搜索結果前幾頁沒有,懶得找了,給個鏈接吧。
知道不方便的話發Hi也行。

『貳』 關於python 函數嵌套

因為最後的那句return nested。

tester()()會自動調用它的返回值,而此時的返回值為nested,即def nested()這個函數,所以自然而然執行到了裡面的print語句。
你可以試試把最後那就return nested改成其他的如return nestedxxx,再tester()()時就會報錯了。
另外,在python里對於方法ester和nested是沒有tester().nested()這種用法的,所以這樣輸入肯定報錯的,如果ester和nested是類(class)的話才有這種寫法。

希望對你有所幫助~~

『叄』 python 函數嵌套

函數a返回的是一個函數對象,c = a(3)那麼c是一個函數b對象,可以調用,c(2)則調用此函數,函數的內容是計算x+y然後返回,x來自於外層閉包a(3)中的參數3,y來自於c(2)中的參數2,故2+3=5,返回5。

『肆』 python 定義函數

python 定義函數:
在Python中,可以定義包含若干參數的函數,這里有幾種可用的形式,也可以混合使用:

1. 默認參數
最常用的一種形式是為一個或多個參數指定默認值。

>>> def ask_ok(prompt,retries=4,complaint='Yes or no Please!'):
while True:
ok=input(prompt)
if ok in ('y','ye','yes'):
return True
if ok in ('n','no','nop','nope'):
return False
retries=retries-1
if retries<0:
raise IOError('refusenik user')
print(complaint)

這個函數可以通過幾種方式調用:
只提供強制參數
>>> ask_ok('Do you really want to quit?')
Do you really want to quit?yes
True

提供一個可選參數
>>> ask_ok('OK to overwrite the file',2)
OK to overwrite the fileNo
Yes or no Please!
OK to overwrite the fileno
False

提供所有的參數
>>> ask_ok('OK to overwrite the file?',2,'Come on, only yes or no!')
OK to overwrite the file? test
Come on, only yes or no!
OK to overwrite the file?yes
True

2. 關鍵字參數
函數同樣可以使用keyword=value形式通過關鍵字參數調用

>>> def parrot(voltage,state='a stiff',action='voom',type='Norwegian Blue'):
print("--This parrot wouldn't", action, end=' ')
print("if you put",voltage,"volts through it.")
print("--Lovely plumage, the",type)
print("--It's",state,"!")

>>> parrot(1000)
--This parrot wouldn't voom if you put 1000 volts through it.
--Lovely plumage, the Norwegian Blue
--It's a stiff !
>>> parrot(action="vooooom",voltage=1000000)
--This parrot wouldn't vooooom if you put 1000000 volts through it.
--Lovely plumage, the Norwegian Blue
--It's a stiff !
>>> parrot('a thousand',state='pushing up the daisies')
--This parrot wouldn't voom if you put a thousand volts through it.
--Lovely plumage, the Norwegian Blue
--It's pushing up the daisies !

但是以下的調用方式是錯誤的:

>>> parrot(voltage=5, 'dead')
SyntaxError: non-keyword arg after keyword arg
>>> parrot()
Traceback (most recent call last):
File "<pyshell#57>", line 1, in <mole>
parrot()
TypeError: parrot() missing 1 required positional argument: 'voltage'
>>> parrot(110, voltage=220)
Traceback (most recent call last):
File "<pyshell#58>", line 1, in <mole>
parrot(110, voltage=220)
TypeError: parrot() got multiple values for argument 'voltage'
>>> parrot(actor='John')
Traceback (most recent call last):
File "<pyshell#59>", line 1, in <mole>
parrot(actor='John')
TypeError: parrot() got an unexpected keyword argument 'actor'
>>> parrot(voltage=100,action='voom',action='voooooom')
SyntaxError: keyword argument repeated

Python的函數定義中有兩種特殊的情況,即出現*,**的形式。
*用來傳遞任意個無名字參數,這些參數會以一個元組的形式訪問
**用來傳遞任意個有名字的參數,這些參數用字典來訪問
(*name必須出現在**name之前)

>>> def cheeseshop1(kind,*arguments,**keywords):
print("--Do you have any",kind,"?")
print("--I'm sorry, we're all out of",kind)
for arg in arguments:
print(arg)
print("-"*40)
keys=sorted(keywords.keys())
for kw in keys:
print(kw,":",keywords[kw])

>>> cheeseshop1("Limbuger","It's very runny, sir.","It's really very, very runny, sir.",shopkeeper="Michael Palin",client="John",sketch="Cheese Shop Sketch")
--Do you have any Limbuger ?
--I'm sorry, we're all out of Limbuger
It's very runny, sir.
It's really very, very runny, sir.
----------------------------------------
client : John
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
>>>

3. 可變參數列表
最常用的選擇是指明一個函數可以使用任意數目的參數調用。這些參數被包裝進一個元組,在可變數目的參數前,可以有零個或多個普通的參數
通常,這些可變的參數在形參列表的最後定義,因為他們會收集傳遞給函數的所有剩下的輸入參數。任何出現在*args參數之後的形參只能是「關鍵字參數」
>>> def contact(*args,sep='/'):
return sep.join(args)

>>> contact("earth","mars","venus")
'earth/mars/venus'

4. 拆分參數列表
當參數是一個列表或元組,但函數需要分開的位置參數時,就需要拆分參數
調用函數時使用*操作符將參數從列表或元組中拆分出來
>>> list(range(3,6))
[3, 4, 5]
>>> args=[3,6]
>>> list(range(*args))
[3, 4, 5]
>>>

以此類推,字典可以使用**操作符拆分成關鍵字參數

>>> def parrot(voltage,state='a stiff',action='voom'):
print("--This parrot wouldn't", action,end=' ')
print("if you put",voltage,"volts through it.",end=' ')
print("E's", state,"!")

>>> d={"voltage":"four million","state":"bleedin' demised","action":"VOOM"}
>>> parrot(**d)
--This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

5. Lambda
在Python中使用lambda來創建匿名函數,而用def創建的是有名稱的。
python lambda會創建一個函數對象,但不會把這個函數對象賦給一個標識符,而def則會把函數對象賦值給一個變數
python lambda它只是一個表達式,而def則是一個語句

>>> def make_incrementor(n):
return lambda x:x+n

>>> f=make_incrementor(42)
>>> f(0)
42
>>> f(2)
44

>>> g=lambda x:x*2
>>> print(g(3))
6
>>> m=lambda x,y,z:(x-y)*z
>>> print(m(3,1,2))
4

6. 文檔字元串
關於文檔字元串內容和格式的約定:
第一行應該總是關於對象用途的摘要,以大寫字母開頭,並且以句號結束
如果文檔字元串包含多行,第二行應該是空行

>>> def my_function():
"""Do nothing, but document it.

No, really, it doesn't do anything.
"""
pass

>>> print(my_function.__doc__)
Do nothing, but document it.

No, really, it doesn't do anything.

『伍』 Python-嵌套函數中的局部變數

嵌套函數在執行時(而不是在定義時)從父范圍中查找變數。
編譯函數主體,然後驗證「自由」變數(未在函數本身中通過賦值定義),然後將其作為閉包單元綁定到函數,並且代碼使用索引引用每個單元格。pet_function因此具有一個自由變數(cage),然後將其通過一個閉合單元引用,索引為0的閉合本身指向局部變數cage在get_petters功能。
當你實際調用該函數時,該閉包將用於在你調用該函數時查看cage周圍作用域中的值。問題就在這里。在你調用函數時,該函數已經完成了對其結果的計算。將在在執行過程中的一些點局部變數分配各的,和字元串,但在功能的結束,包含了最後一個值。因此,當你調用每個動態返回的函數時,就會得到列印的值。get_petterscage'cow''dog''cat'cage'cat''cat'
解決方法是不依賴閉包。你可以改用部分函數,創建新的函數作用域或將變數綁定為關鍵字parameter的默認值。
部分函數示例,使用functools.partial():
from functools import partialdef pet_function(cage=None):
print "Mary pets the " + cage.animal + "."yield (animal, partial(gotimes, partial(pet_function, cage=cage)))

創建一個新的范圍示例:
def scoped_cage(cage=None):
def pet_function():
print "Mary pets the " + cage.animal + "."
return pet_functionyield (animal, partial(gotimes, scoped_cage(cage)))

將變數綁定為關鍵字參數的默認值:
def pet_function(cage=cage):
print "Mary pets the " + cage.animal + "."yield (animal, partial(gotimes, pet_function))

無需scoped_cage在循環中定義函數,編譯僅進行一次,而不是在循環的每次迭代中進行。

『陸』 函數嵌套是指 ,遞歸是指 。

函數嵌套。。一般提到這個有兩個意思,有的語言運行函數嵌套那就是函數的嵌套,指在一個函數體里定義另一個函數,比如python
def outer():
name="python"

def inner():
print name
return inner()

有的語言不允許函數嵌套,那指的就是函數嵌套調用。比如c語言的
int a()
{
b();//調用函數b

}

遞歸的話就是自己調用自己
int a(int x){
if(x==5)return 0; //一定要有結束條件不然遞歸就爆內存的

x++;

a(x);

}
調用函數
a(0); //那麼遞歸過程是a(0)--->a(1)--->a(2)--->a(3)--->a(4)--->a(5)

『柒』 有關python的定義求均值的嵌套函數。

*args就是接收不限定個數的參數,輸入的話就被x接收了。x這里默認是一個列表,或者元組/

『捌』 python的函數里還可以定義函數嗎

這個肯定可以的。閉包、裝飾器都是在函數里又定義了個函數,普通的函數也是可以嵌套定義的。

『玖』 python 兩個函數嵌套問題找bug

我試著運行了,報錯是fixedPoint函數沒有定義。

函數得先定義後使用。舉例:

deffixedPoint(x,y):
returnx

defsqrt(a):
deftryit(x):
return0.5*(a/x+x)
returnfixedPoint(tryit(a),0.0001)

printsqrt(1)

『拾』 Python 為什麼要使用函數嵌套函數

查看一下柯里化的定義,這樣寫返回的新函數能夠保持當時的狀態,而且能夠達到惰性求值的效果(用到這個函數的時候再處理傳入的參數)

閱讀全文

與python函數嵌套定義相關的資料

熱點內容
單片機代碼跳掉 瀏覽:447
程序員談薪水壓價 瀏覽:861
榮耀10青春版支持方舟編譯啊 瀏覽:158
最優估計pdf 瀏覽:826
androiddrawtext字體 瀏覽:669
c語言源編輯源程序編譯 瀏覽:821
手裡捏東西真的可以解壓嗎 瀏覽:265
編譯原理畫狀態表 瀏覽:28
用echo命令產生下列輸出 瀏覽:358
在內網如何訪問伺服器 瀏覽:959
java導入oracle資料庫 瀏覽:132
堅朗內開內倒鋁條演算法 瀏覽:259
華為閱讀新建文件夾 瀏覽:770
幻塔如何選擇伺服器 瀏覽:221
解壓先把文件壓到系統盤 瀏覽:822
access壓縮和修復資料庫 瀏覽:791
光纖交換機命令 瀏覽:513
白色桌放什麼文件夾 瀏覽:296
分治演算法思想 瀏覽:151
s曲線加減速演算法 瀏覽:403