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

創(chuàng)新互聯從2013年成立,先為湖北等服務建站,湖北等地企業(yè),進行企業(yè)商務咨詢服務。為湖北企業(yè)網站制作PC+手機+微官網三網同步一站式服務解決您的所有建站問題。
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、為了將變量標記為自由變量,可以使用nonlocal語句進行聲明,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學習指路:創(chuàng)新互聯Python教程
本文教程操作環(huán)境:windows7系統(tǒng)、Python 3.9.1,DELL G3電腦。
分享題目:創(chuàng)新互聯Python教程:python自由變量是什么
文章網址:http://www.5511xx.com/article/djodghg.html


咨詢
建站咨詢
