iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 11
0

變數範圍分為4種(LEGB)

  • Local
    • 出現在function宣告之內(def, lambda)且未使用global關鍵字的變數
    • para1, var2, para2, var3
  • Enclosing-function locals
    • 若變數名稱相同,由內向外找
    • var3
  • Global
    • 這邊的global指的是以一個python檔案(module)為範圍。
    • 任何在該module內且出現在function宣告之外的變數
    • function宣告之內使用global關鍵字的變數
    • var1, var5
  • Built-in
    • python內建關鍵字,可以跨越python檔案(module)的範圍
    • python 3中可以使用builtins module檢視
var1 = 10


def demo(para1):
    var2 = 100
    print('var1 is {}, it\'s global in demo module(file)'.format(var1))
    print('para1 is {}, it\' lobal in demo function'.format(para1))
    print('var2 is {}, it\' lobal in demo function'.format(var2))


demo(50)

# var1 is 10, it's global in demo module(file)
# para1 is 50, it' lobal in demo function
# var2 is 100, it' lobal in demo function


try:
    print('para1 is {}'.format(para1))
except NameError as e:
    print('Name Error: {0}'.format(e))

try:
    print('var2 is {}'.format(var2))
except NameError as e:
    print('Name Error: {0}'.format(e))

# Name Error: name 'para1' is not defined
# Name Error: name 'var2' is not defined
def demo2(para2):
    var3 = 66
    global var5
    var5 = 33

    def demo3():
        var3 = 22
        var4 = 88
        print('var3: {}'.format(var3))
        print('var4: {}'.format(var4))
        print('sum of var3 and var4: {}'.format(var3 + var4))
        
    demo3()

demo2(10)
# var3: 22
# var4: 88
# sum of var3 and var4: 110
# var5: 33


demo3()
# NameError: name 'demo3' is not defined
builtins_name = dir(builtins)
print('{}'.format(builtins_name))
print('len of builtins_name is {}'.format(len(builtins_name)))
print('{}'.format('NameError' in builtins_name))

# ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
# len of builtins_name is 151
# True

參考


上一篇
Day19-Function-lambda和decorator語法糖
下一篇
Day21-File-概觀
系列文
if len(learning.python) == 30:31

尚未有邦友留言

立即登入留言