Twenty-five function object

Twenty-five function object

First, the in-depth understanding of the function

  • Everything in 1.python objects, functions are first-class objects

  • 2. Since the function is an object, the function can be treated as data processing

def f():
    pass

# 函数名就可以看作是一种数据类型的变量
print(f)
print(id(f))
print(type(f))
'''
<function f at 0x00000181D80A2BF8>
1657186954232
<class 'function'>
'''

# 函数名加() 就是返回值,所有的属性都根据函数的返回值而定
print(f())
print(id(f()))
print(type(f()))
'''
None
1408672976
<class 'NoneType'>
'''
  • Function is the function name can be seen as an object, when you call it, it must be added in parentheses behind

Second, the four functions function object

1. references

  • Similar to the variable, function object can be used as reference values ​​of variables to deal with
def f():
    pass

x = f
print(x)
# <function f at 0x0000024E66002BF8>

2. as a parameter passed to the function

  • Since the function object like variables, it also can be used as a variable name to receive data by value
def f():
    print('通过x()来实现f函数的调用')

def f2(x):
    x()
    
f2(f)
# 通过x()来实现f函数的调用

3. as a return value of the function

  • And a function object as a parameter value, the function object can function as a return value
def f(x):
    return x
def f2():
    print('我是f2')
a = f(f2)
a()  # 我是f2

4. The container type as element

  • Also function object can be regarded as a value, so it can be stored as an element in a container type
def f():
    print('你好')

lis = [f]
lis[0]()  # 你好

Third, the application function object

def pay():
    print('支付成功')
    
def withdraw():
    print('提现成功')
    
func_dic = {'0': par, '1': withdraw}

while True:
    msg = """
        '1': 支付,
        '2': 提现,
        '3': 退出,
          """
    print(msg)
    choice = input('选择功能:').strip()
    if choice == '3':
        break
    elif choice in func_dic:
        func_dic[choice]()

Guess you like

Origin www.cnblogs.com/itboy-newking/p/10953491.html