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