亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何訪問python3中的上限值?

如何訪問python3中的上限值?

一只甜甜圈 2022-12-02 17:20:44
在 JavaScript 中,此代碼返回 4:let x = 3;let foo = () => {  console.log(x);}let bar = () => {  x = 4;  foo();}bar();但 Python3 中的相同代碼返回 3:x = 3def foo():  print(x)def bar():  x = 4  foo()bar()https://repl.it/@brachkow/python3scope為什么以及如何運作?
查看完整描述

4 回答

?
慕斯709654

TA貢獻1840條經驗 獲得超5個贊

要分配給 global x,您需要global xbar函數中聲明。



查看完整回答
反對 回復 2022-12-02
?
慕絲7291255

TA貢獻1859條經驗 獲得超6個贊

如果在全局范圍內定義的變量名稱也在函數的局部范圍內使用,則會發生兩件事:


您正在進行讀取操作(例如:簡單地打印它),那么變量引用的值與全局對象相同

x = 3


def foo():

  print(x)


foo()


# Here the x in the global scope and foo's scope both point to the same int object


您正在進行寫操作(示例:為變量賦值),然后在函數的局部范圍內創建一個新對象并引用它。這不再指向全局對象

x = 3


def bar():

  x = 4


bar()


# Here the x in the global scope and bar's scope points to two different int objects

但是,如果你想在全局范圍內使用一個變量并想在局部范圍內對其進行寫操作,你需要將它聲明為global


x = 3


def bar():

  global x

  x = 4


bar()


# Both x points to the same int object


查看完整回答
反對 回復 2022-12-02
?
qq_花開花謝_0

TA貢獻1835條經驗 獲得超7個贊

很明顯,程序,機器在映射中工作


bar()


# in bar function you have x, but python takes it as a private x, not the global one

def bar():

  x = 4

  foo()


# Now when you call foo(), it will take the global x = 3 

# into consideration, and not the private variable [Basic Access Modal]

def foo():

   print(x)


# Hence OUTPUT

# >>> 3

現在,如果你想打印4, not 3,這是全局的,你需要在 foo() 中傳遞私有值,并使 foo() 接受一個參數


def bar():

  x = 4

  foo(x)


def foo(args):

   print(args)


# OUTPUT

# >>> 4

或者


global在你的內部使用bar(),這樣機器就會明白xbar 的內部是全局 x,而不是私有的


def bar():

  # here machine understands that this is global variabl

  # not the private one

  global x = 4

  foo()


查看完整回答
反對 回復 2022-12-02
?
交互式愛情

TA貢獻1712條經驗 獲得超3個贊

使用全局關鍵字


x = 3

def foo:

    global x

    x = 4

    print(x)

foo()


查看完整回答
反對 回復 2022-12-02
  • 4 回答
  • 0 關注
  • 158 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號