7.10 function object

Functions are first-class objects: point function name as the parameter value may be passed

 

In python, the values ​​of all variables stored as long as the address, we will call the object.

  - All variables are used to store the address, it is an object

  - storage address is integer integer object that holds the address of the function is a function object,

    Store the address of the file is a file object

Function object: variable holds the address of the function is the function object

DEF func ():       # Here func is the function object 
    pass

1. The function name may be transferred

name = ' Bitten ' 
X = name
 Print (X)   # Bitten 
Print (ID (X))   # 4,537,026,352 
DEF FUNC ():
     Print ( ' from FUNC ' )
 Print (ID (FUNC))   # 4,536,540,696 

F = FUNC   # Function Name can pass, f is equivalent to the following func

Print (func)   # <function func AT 0x10154ae18> 
func ()   # from func 
Print (F)   # <function func AT 0x10e974e18> 
      # is actually directed to a function member function func code memory address
F () # from func

2. The function name can be passed as parameters to other functions

def func():
    print('from func')

def index(args):
    print(args)  # <function func at 0x101b80e18>
    args()  # from func
    print('from index')  # from index
index(func)

3. The function name may be used as the return value of the function

def index():
    print('index')

def func():
    print('func')
    return index
res = func()  # func
print(res)  # <function index at 0x108027e18>
res()  # index

4. The function name may be used as container type parameter

def register():
    username = input()
    pwd = input()
def login():
    print('login...')

msg ='''
1. Registration
2. Log
'''
func_dict = {
    '1':register,
    '2':login,

}
while True:
    print(msg)
    Choice = the INPUT ( ' select >>> to perform: ' ) .strip ()   # to space 
    IF Choice in func_dict:
        func_dict.get(choice)()
    the else :
         Print ( ' This function is not ' )

 

Guess you like

Origin www.cnblogs.com/PowerTips/p/11165765.html