First Class Objects

First-class functions:在程式語言中,functions可以被當作是一個物件或變數。

因此,Python中的functions是first-class objects。並具有下列幾項功能:

  1. 指派到一個變數:

    def hello():
        print("Hello World")
    
    greet = hello
    greet()
    
    --------------------------------------------------
    # Hello World
    
  2. 可以將一個function當作另一個functions的參數(argument):

    (The same idea from Calculus or discrete math - composite function.)

    def hello():
        print("Hello World")
    
    def call_another_function(other_func):
        # other_func = hello
        other_func()
    
    call_another_function(hello)
    
    --------------------------------------------------
    # Hello World
    
    def square(num):
        return num ** 2
    
    my_list = [1, 2, 3, 4]
    result = map(square, my_list)
    for i in result:
    		print(i)
    
    --------------------------------------------------
    # 1
    # 4
    # 9
    # 16
    
  3. functions可以回傳一個function。

    def hello():
        def greet():
            print("greet!!")
        return greet
    
    welcome = hello()
    welcome()
    
    --------------------------------------------------
    # greet!!
    
    def hello(name):
        def greet(another_name):
            print("hello, " + another_name)
    
        def bye(another_name):
            print("bye, " + another_name)
    
        if name == "greet":
            return greet
        else:
            return bye
    
    welcome = hello("greet")
    goodbye = hello("something else")
    welcome("Wilson")
    goodbye("Grace")
    
    --------------------------------------------------
    # hello, Wilson
    # bye, grace
    
  4. 可以放入list、tuple或dictionary。

    def hello():
        print("hello 1")
    
    def hello2():
        print("hello 2")
    
    for func in [hello, hello2]:
        func()
    
    --------------------------------------------------
    # hello 1
    # hello 2
    

Decorators

Generator

Recall the generator syntax that we learned from chapter 3. (The one that is very similar to comprehension.)

Iteration, Iterable, and Iterator