1. 程式人生 > >函式程式設計(名稱空間,閉包,裝飾器,)

函式程式設計(名稱空間,閉包,裝飾器,)

一、名稱空間

名稱空間 namespace 

存放名字的地方

x=1 名稱空間存放 x 和 x與1繫結關係 類似{x:id(1)}

1.1.
名稱空間分三種:
  1.locals 是函式內的名稱空間,包括區域性變數和形參 locals() 
  2.globals 列印程式指令碼的所有變數 globals()
  3.builtins 內建模組的名字空間 python 一啟動自帶的那些自帶函式 len() ord() dir(__builtins__)

1.2.
dir(__builtins__) #pythond的內建方法

['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', 'WindowsError', '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']

1.3.
名稱空間 與 作用域 有很大的關係
不同變數的作用域不同就是由這個變數所在的名稱空間決定的

作用域即範圍scope
全域性範圍:全域性存活 全域性有效
區域性範圍:臨時存活 區域性有效
檢視作用域範圍 globals() locals()

1.4.
作用域的查詢順序:
LEGB
L: local 函式內的名稱空間 
E: enclosing 外部巢狀函式的名稱空間 
G: global 全域性變數 函式定義所在模組的名稱空間 
B: builtins 內建模組的名稱空間

二、閉包

def func():
    n = 10
    def fun2():
        print(
'fun2:',n) return fun2 res = func() print(res) res() ---- <function func.<locals>.fun2 at 0x000001BB92CDFA60> fun2: 10

閉包:函式內部的子函式返回,在外部呼叫子函式時,其實函式已經結束,但是在呼叫子函式時,函式內部的區域性變數任然有效。

三、裝飾器

參考:http://www.cnblogs.com/alex3714/articles/5765046.html
youporn.com

軟體開發 的 一個原則:“開放-封閉”原則
    開放:對現有功能的擴充套件開放
    封閉:已實現的功能程式碼塊不應該被修改 
帶引數的裝飾器

--------------
# 語法糖 裝飾器
user_status = False
def login(func): #henan

    def inner():
        _username = 'alice'
        _password = '123'
        global user_status

        if user_status == False:
            username = input('username:').strip()
            password = input('password:').strip()
            if username == _username and password == _password:
                print('welcome login...')
                user_status = True
            else:
                print('Wrong username or password!')
        else:
            print("使用者已經登入,驗證通過...")

        if user_status == True:
            func()  # 驗證通過就呼叫相應的功能

    return inner


def home():
    print("---首頁----")
@login
def america():
    print("----歐美專區----")
def japan():
    print("----日韓專區----")
@login # henan = login(henan)
def henan():
    print("----河南專區----")

home()
henan()
america()
----------------
# 帶引數的裝飾器
user_status = False
def login(func): #henan

    def inner(arg):
        _username = 'alice'
        _password = '123'
        global user_status

        if user_status == False:
            username = input('username:').strip()
            password = input('password:').strip()
            if username == _username and password == _password:
                print('welcome login...')
                user_status = True
            else:
                print('Wrong username or password!')
        else:
            print("使用者已經登入,驗證通過...")

        if user_status == True:
            func(arg)  # 驗證通過就呼叫相應的功能

    return inner


def home():
    print("---首頁----")
@login
def america():
    print("----歐美專區----")
def japan():
    print("----日韓專區----")
@login # henan = login(henan)
def henan(style):
    print("----河南專區----",style)

home()
henan('3p')
-------------------
# 裝飾器 有的帶引數 有的不帶引數 非固定引數 支援多個引數
user_status = False
def login(func): #henan

    def inner(*args,**kwargs):
        _username = 'alice'
        _password = '123'
        global user_status

        if user_status == False:
            username = input('username:').strip()
            password = input('password:').strip()
            if username == _username and password == _password:
                print('welcome login...')
                user_status = True
            else:
                print('Wrong username or password!')
        else:
            print("使用者已經登入,驗證通過...")

        if user_status == True:
            func(*args,**kwargs)  # 驗證通過就呼叫相應的功能

    return inner


def home():
    print("---首頁----")
@login
def america():
    print("----歐美專區----")
@login
def japan(x,y='abc'):
    print("----日韓專區----",x,y)
@login # henan = login(henan)
def henan(style):
    print("----河南專區----",style)

home()
henan('3p')
america()
japan(2,'asa')
--------------------
# 帶引數的裝飾器 又包一層
user_status = False
def login(auth_type): #henan
    print('asa')
    def outer(func): #henan
        def inner(*args,**kwargs):
            _username = 'alice'
            _password = '123'
            global user_status

            if user_status == False:
                username = input('username:').strip()
                password = input('password:').strip()
                if username == _username and password == _password:
                    print('welcome login...')
                    user_status = True
                else:
                    print('Wrong username or password!')
            else:
                print("使用者已經登入,驗證通過...")

            if user_status == True:
                func(*args,**kwargs)  # 驗證通過就呼叫相應的功能

        return inner

    return outer


def home():
    print("---首頁----")
@login('wx')
def america():
    print("----歐美專區----")
@login('wb')
def japan(x,y='abc'):
    print("----日韓專區----",x,y)
@login ('qq') # henan =login('qq')(henan) = inner
def henan(style):
    print("----河南專區----",style)

home()
henan('3p')
america()