LoginSignup
2

More than 3 years have passed since last update.

グローバル変数とローカル変数2

Last updated at Posted at 2020-01-19
1
player = '太郎'

def f():
    player = '次郎'
    print('local:', locals())

f()
print(player)
1の実行結果
local: {'player': '次郎'}
太郎

ローカル変数を宣言しないで、
locals()を実行すると、

2
player = '太郎'

def f():
    print('local:', locals())

f()
print(player)
2の実行結果
local: {}
太郎

空の辞書がかえってくる。

globals()も実行してみると、

3
player = '太郎'

def f():
    print('local:', locals())

f()
print('global:', globals())
3の実行結果
local: {}
global: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7efff584a2b0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'Main.py', '__cached__': None, 'player': '太郎', 'f': <function f at 0xxxxxxxxxxxxx>}

たくさん出てくるが、
'player': '太郎'と出ている。

他に__name____main__であるとか、
__doc__は何も入っていなくてNoneであるとか
事前に宣言されているものがでてくる。

ここでこのファンクションにドキュメントを書いてみると、

4
"""
test ##################
"""

player = '太郎'

def f():
    print('local:', locals())

f()
print('global:', globals())
4の実行結果
local: {}
global: {'__name__': '__main__', '__doc__': '\ntest ##################\n', '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f73121652b0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'Main.py', '__cached__': None, 'player': '太郎', 'f': <function f at 0x7f7312236e18>}

__doc__が'\ntest ##################\nとなった。

関数内の__name____doc__も見てみると、

5
player = '太郎'

def f():
    """Test func doc"""
    print(f.__name__)
    print(f.__doc__)

f()
print('global:', __name__)
5の実行結果
f
Test func doc
global: __main__

まず、
print(f.__name__)
で関数fの名前が出力され、
次に、
print(f.__doc__)で関数fのドキュメントが出力される。
最後に、
print('global:', __name__)
文字列'global:'に続いて全体ファンクションの名前が出力される。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2