1. 程式人生 > >函數對象

函數對象

you draw hat gin 函數 tin UNC logout bar

函數對象

#1-函數可以的作為數據被引用

def foo():
print("from foo")
foo()

print(foo)
func = foo
print(func)
func()

#2-可以當作一個函數傳給另外一個函數

def foo():
print("from foo")
foo()

def bar(x):
print(x)
x() # x() = foo()
bar(foo) #foo 作為實參傳給了x

#3-可以當作函數的返回值

def foo():
print("from foo")

def bar():
return foo
f=bar()
print(f is foo )
f()

#4-可以當作容器類元素
def f1():
print("from f1")

def f2():
print("from f2")

def f3():
print("from f3")

l=[f1,f2,f3]
print(l)
l[0]()

#5-購物場景
def auth():
print("please login")

def shopping():
print("chose what you want")

def withdraw():
print("get your money")

def leave():
print("please logout")

func_dic={
‘1‘: auth,
‘2‘: shopping,
‘3‘: withdraw,
‘4‘: leave
}
while True:
print("""
1:登錄
2:購物
3:轉賬
4:退出
""")

choice = input(‘請輸入您要執行的操作:‘).strip() # choice=‘123‘
if choice == ‘0‘: break
if choice not in func_dic:
print(‘輸入錯誤的指令,請重新輸入‘)
continue

func_dic[choice]()

---恢復內容結束---

---恢復內容結束---

函數對象