python函数名与变量名可以一样吗_python--第一类对象,函数名,变量名
一 . 第一類對象
函數對象可以像變量一樣進行賦值 ,?還可以作為列表的元素進行使用
可以作為返回值返回 , 可以作為參數進行傳遞
def func():
def people():
print('金_卡戴珊')
print('oh,yes!')
print('oh,baby!')
return people
ret = func()
ret()
二 . 閉包
閉包 -> 函數的嵌套
內層函數對外層函數中的變量的使用
好處:
1. 保護變量不被侵害
2. 讓一個變量常駐內存
如何通過代碼查看一個閉包
__closure__: 有東西就是閉包. 沒東西就不是閉包
def wrapper():
name = "周杰倫" # 局部變量常駐與內存
def inner():
print(name) # 在內層函數中使用了外層函數的局部變量
print(inner.__closure__) # 有東西就是閉包
return inner # 返回函數名
# inner()
ret = wrapper() # ret是一個內層函數
ret() # ret是inner, 執行的時機是不確定的, 必須保證里面的name必須存在
三 . 迭代器
迭代器 -> 固定的思路. for循環
一個數據類型中包含了__iter__函數表示這個數據是可迭代的
dir(數據): 返回這個數據可以執行的所有操作
判斷迭代器和可迭代對象的方案(野路子)
__iter__ 可迭代的
__iter__ __next__ 迭代器
lst =['吳彥祖','謝霆鋒','阿湯哥','郭達','岳云鵬']
it = lst.__iter__()
print(it.__next__())
print(it.__next__())
print(it.__next__())
print(it.__next__())
print(it.__next__())
print(it.__next__())
判斷迭代器和可迭代對象的方案(官方)
from collections import Iterable, Iterator
isinstance(對象, Iterable) 是否是可迭代的
isinstance(對象, Iterator) 是否是迭代器
lst = [1,2,3]
# print(lst.__next__())
print(isinstance(lst, Iterable)) # xxx是否是xxx類型的. True
print(isinstance(lst, Iterator)) # False
it = lst.__iter__() # 迭代器一定可迭代, 可迭代的東西不一定是迭代器
print(isinstance(it, Iterable)) # xxx是否是xxx類型的. True
print(isinstance(it, Iterator)) # True
模擬for循環
lst = ["海爾兄弟", "阿童木", "葫蘆娃", "舒克貝塔", "大風車"]
# 模擬for循環 for el in lst:
it = lst.__iter__() # 獲取到迭代器0
while 1: # 循環
try: # 嘗試
el = it.__next__() # 那數據
print(el)
except StopIteration: # 出了錯誤, 意味著數據拿完了
break # 結束循環
總結
以上是生活随笔為你收集整理的python函数名与变量名可以一样吗_python--第一类对象,函数名,变量名的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: cad完全卸载教程_CAD室内设计中厨房
- 下一篇: 【Pytorch神经网络理论篇】 28