新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:python自由變量是什么
1、自由變量是指未綁定到本地作用域的變量。如果自由變量綁定的值是可變的,變量仍然可以在封閉包中操作。如果是不可變的(數(shù)字、字符串等。),在封閉包中重新綁定自由變量會(huì)出錯(cuò)。

創(chuàng)新互聯(lián)從2013年成立,先為湖北等服務(wù)建站,湖北等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為湖北企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。
def make_averager(): count = 0 total = 0 def averager(new_value): count += 1 total += new_value return total / count return averager >>> avg = make_averager() >>> avg(10) Traceback (most recent call last): ... UnboundLocalError: local variable 'count' referenced before assignment
2、為了將變量標(biāo)記為自由變量,可以使用nonlocal語句進(jìn)行聲明,nonlocal語句可以解決。
def make_averager(): count = 0 total = 0 def averager(new_value): nonlocal count, total # 聲明count、total為自由變量 count += 1 total += new_value return total / count return averager
以上就是python自由變量的介紹,希望對大家有所幫助。更多Python學(xué)習(xí)指路:創(chuàng)新互聯(lián)Python教程
本文教程操作環(huán)境:windows7系統(tǒng)、Python 3.9.1,DELL G3電腦。
本文名稱:創(chuàng)新互聯(lián)Python教程:python自由變量是什么
網(wǎng)站網(wǎng)址:http://www.dlmjj.cn/article/djodghg.html


咨詢
建站咨詢
