类和函数中全局变量的可访问性

时间:2018-01-22 04:36:34

标签: python scope global-variables

我对__中以Python开头的全局变量感到困惑。我想知道为什么__XXX

中无法访问class function等变量

这是我的代码:

__global_var = 'first'
global_var = 'second'

class TestClass(object):
    """docstring for Test"""
    def __init__(self):
        global __global_var
        global global_var
        print global_var, __global_var


def test_func():
    global __global_var
    global global_var
    print global_var, __global_var

if __name__ == '__main__':
    test_func()
    test_class = TestClass()

输出是:

second first
second
Traceback (most recent call last):
  File "test_global.py", line 19, in <module>
    test_class = TestClass()
  File "test_global.py", line 9, in __init__
    print global_var, __global_var
NameError: global name '_TestClass__global_var' is not defined

有人能帮帮我吗?感谢。

0 个答案:

没有答案