6.4 函数对象

6.4 函数对象

python中一切皆是对象,函数名是变量名

  • 变量/函数三个特征
  1. 打印对应的变量值值
  2. id()
  3. type()
def self_max():
    pass

print(self_max)
print(id(self_max))
print(type(self_max))

#self_max就是一个对象

<function self_max at 0x000001FC0C8EC2C0>
2182054068928
<class 'function'>

6.4.1 函数对象的运用

  1. 引用赋值
a='str'
'str'.strip()=a.strip()
#a具有字符串内置方法


def self_max(x,y):
    if x>y:
        return x
    return y

a=self_max 
max_num=a(20,30)

print(max_num)

总结:a等同于函数名self_max,a拥有函数self_max的一切属性

  1. 作为函数返回值
def f2():
    print('f2函数')
    
def f1():
    return f2 #返回函数内存地址
    
print(f1())

f=f1() #f相当于f2
f()

def f1():
    return f2 
def f2():
    print('f2函数')

<function f2 at 0x000001FC0C8EF9C0>
f2函数

总结:

(1)函数定义阶段只检测不运行,f1、f2先后顺序对调不报错

(2)所有函数定义都应在函数调用之前

  1. 作为函数参数

def f1():
    print('f1函数')
def f2 (m): #m=f1
    return m #不加括号

#函数从此处开始逐行运行
f=f2(f1) 
#f1作为参数传给f2,f2开始运行,返回参数f1 赋值给f,f等同于f1

f() #加括号

f1函数
def f1():
    print('f1函数')
def f2 (m): 
    return m #不加括号

f=f2(f1) 
f() #加括号

#--------------------------------------
#等同于上述代码
def f1():
    print('f1函数')
def f2 (m): 
    return m() #加括号
f=f2(f1) 
f #不加括号
  1. 作为容器元素的元素

def f1():
    print('f1函数')
    
l=['str',1,f1]
l[2]()

#函数名当做对象被传递
f1函数

6.4.2 实际应用

# ATM

def trans():
    '''转账'''
    print('trans func')

def withdraw():
    print('withdraw func')

#函数功能选择字典
fun_dict={
    0:trans,
    1:withdraw,
    2:'quit'
}

#功能打印字典
fun_dict_print={
    0:'trans',
    1:'withdraw',
    2:'quit'}

while True:
    print(fun_dict_print)
    choice=int(input('choice>>'))
    
    if choice==2:
        break

    fun_dict[choice]() #函数对象的运用

{0: 'trans', 1: 'withdraw', 2: 'quit'}


choice>> 1


withdraw func
{0: 'trans', 1: 'withdraw', 2: 'quit'}


choice>> 0


trans func
{0: 'trans', 1: 'withdraw', 2: 'quit'}


choice>> 2
posted @ 2025-08-21 10:54  bokebanla  阅读(4)  评论(0)    收藏  举报