Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Pythonのグローバル変数について

kioto
December 09, 2020

 Pythonのグローバル変数について

Start Python Club #64 LT

kioto

December 09, 2020
Tweet

More Decks by kioto

Other Decks in Technology

Transcript

  1. w ϞδϡʔϧείʔϓͰ୅ೖ͞Εͨม਺ w ؔ਺಺ͰࢀরՄೳ άϩʔόϧม਺ͱ͸Կ͔ # -*- coding:utf-8 -*- x

    = 0 # άϩʔόϧม਺ def foo(): print(x) foo() ˞1ZUIPO+BQBOθϩ͔Βͷ1ZUIPOೖ໳ߨ࠲ ʮϩʔΧϧม਺ͱάϩʔόϧม਺ʯΑΓ IUUQTXXXQZUIPOKQUSBJOGVODUJPOMPDBM@WBSIUNM
  2. w ؔ਺಺Ͱ୅ೖͰ͖ͳ͍ w ͦͷ··ͩͱϩʔΧϧม਺ʹͳΔ άϩʔόϧม਺ͱ͸Կ͔ # -*- coding:utf-8 -*- x

    = 0 # άϩʔόϧม਺ def bar(): x = 999 print(x) def foo(): print(x) bar() # => 999 foo() # => 0
  3. ؔ਺಺Ͱάϩʔόϧม਺Λ୅ೖ w HMPCBMจΛ࢖͏ # -*- coding:utf-8 -*- x = 0

    def bar(): global x x = 10 def foo(): print(x) bar() foo() # => 10
  4. HMPCBMจͷఆٛ # -*- coding:utf-8 -*- x = 0 def bar():

    global x x = 10 def foo(): print(x) bar() foo() # => 10  HMPCBMจ͸ɺݱࡏͷίʔυϒϩο ΫશମͰҡ࣋͞ΕΔએݴจͰ͢ɻ  ݱࡏͷίʔυϒϩοΫ w  HMPCBMจ͸ɺྻڍͨࣝ͠ผࢠΛ άϩʔόϧม਺ͱͯ͠ղऍ͢ΔΑ͏ࢦ ఆ͢Δ͜ͱΛҙຯ͠·͢ɻ  ྻڍͨࣝ͠ผࢠ
  5. ʢඇਪ঑ʣϞδϡʔϧείʔϓͰະఆٛ w ౰વɺઌʹࢀর͢ΔͱΤϥʔ # -*- coding:utf-8 -*- # x =

    0 def bar(): global x x = 10 def foo(): print(x) foo() # ERROR! bar()
  6. ʢඇਪ঑ʣࢀর͚ͩͳͷʹHMPCBMจ w Մಡੑ͕ѱ͘ͳΔ w ୅ೖ͢Δͭ΋Γͩͬͨʁόάʁ # -*- coding:utf-8 -*- x

    = 0 def bar(): global x x = 10 # xʹ୅ೖ͍ͯ͠Δ def foo(): global x print(x) # x͸୅ೖ͠ͳ͍ͷʁ bar() foo() # => 10
  7. ଞͷϞδϡʔϧείʔϓͷม਺ࢀর w Α༷ͦͷάϩʔόϧม਺Λ࢖͏ # -*- coding:utf-8 -*- import mymod def

    print_val(): print(mymod.val) def set_val(num): mymod.val = num print_val() # => 0 set_val(456) print_val() # => 456 SVOQZ # -*- coding:utf-8 -*- val = 0 NZNPEQZ
  8. ଞͷϞδϡʔϧείʔϓͷม਺ࢀর w Α༷ͦͷάϩʔόϧม਺Λɺࣗ෼ͷͱ͜Ζ ͷάϩʔόϧม਺ͱͯ͠࢖͏ # -*- coding:utf-8 -*- from mymod

    import * def print_val(): print(val) def set_val(num): global val val = num print_val() # => 0 set_val(456) print_val() # => 456 SVOQZ # -*- coding:utf-8 -*- val = 0 NZNPEQZ
  9. ଞͷϞδϡʔϧείʔϓͷม਺ࢀর w ͞Βʹࣗ෼ͷͱ͜ΖͰάϩʔόϧม਺Λ࡞ ΔͱɺNZNPEWBM͕ݟ͑ͳ͘ͳΔ w ͭ·Γ͜͏͍͏ॻ͖ํΛ͢΂͖Ͱͳ͍ # -*- coding:utf-8 -*-

    from mymod import * val = 999 def print_val(): print(val) def set_val(num): global val val = num print_val() # => 999 set_val(456) print_val() # => 456 SVOQZ # -*- coding:utf-8 -*- val = 0 NZNPEQZ
  10. άϩʔόϧม਺ͷࢀর w ̎֊૚ͷؔ਺ఆٛͷྫ # -*- coding:utf-8 -*- x = 0

    def func01(): x = 99 def func02(): # global x print('func02', x) func02() print('func01', x) func01() => func02 99 => func01 99 SFTVMU
  11. άϩʔόϧม਺ͷࢀর w ̎֊૚ͷؔ਺ఆٛͷྫ ʢHMPCBMจ௥Ճʣ # -*- coding:utf-8 -*- x =

    0 def func01(): x = 99 def func02(): global x print('func02', x) func02() print('func01', x) func01() => func02 0 => func01 99 SFTVMU
  12. ༨ஊ w ಉ໊ͷϩʔΧϧม਺ͱάϩʔόϧม਺͸ɺಉ͡είʔϓͰ࢖͑ͳ͍ $ python3 sample.py File "sample.py", line 8

    global x ^ SyntaxError: name 'x' is used prior to global declaration # -*- coding:utf-8 -*- x = 0 def foo(): x = 10 print(x) global x x = 20 print(x) foo() SFTVMU