Python知識點整理(函式篇)

2021-07-14 07:38:33 字數 2731 閱讀 1041

global語句

用於宣告乙個全域性變數

this_is_global = "abc"

def func():

global this_is_global

this_is_global = "global"

print this_is_global

func()

print this_is_global

巢狀作用域

python2.1之前只允許兩個作用域:區域性作用域和全域性作用域。python2.1之後的便支援巢狀作用域,**如下所示:

def foo():

def bar():

print "bar"

n = 4

print m + n

print "foo"

m = 3

bar()

foo()

輸出:

foo

bar 7

以下**會報錯:

def foo():

def bar():

print "bar"

n = 4

print m + n

print "foo"

bar()

m = 3

foo()

錯誤:nameerror: free variable 'm' referenced before assignment in enclosing scope

2.全域性變數能被同名的區域性變數所覆蓋;

3.變數的作用域受到命名空間的影響。

如果在乙個內部函式裡,對在外部的非全域性作用域的變數進行引用,那麼內部函式就被認為是 closure(閉包)。使用閉包來代替類實現某個功能是個不錯的注意。

計數器:

def counter(start_at = 0):

count = [start_at]

def incr():

count[0] += 1

return count[0]

return incr

count1 = counter(5) #新建函式物件

print count1()

print count1()

print count1()

count2 = counter(5) #新建函式物件

print count2()

print count2()

print count1()

print count1()

print count1()

輸出:6 7

8 67 9

10 11

驗證器:

def max_length(n):

def validator(s):

if len(s) < n:

return

raise exception('length of string must be less than !'.format(n))

return validator

簡版:

def ******gen():

yield 1

yield "2->punch!"

myg = ******gen()

print myg.next()

print myg.next()

for迴圈版:

from random import randint

def randgen(alist):

while len(alist) > 0:

yield alist.pop(randint(0, len(alist) - 1))

for item in randgen(['rock', '*****', 'scissors']):

print item

任務佇列:

def tt():

for x in xrange(4):

yield "tt+" + str(x)

def yy():

for x in xrange(4):

yield "yy+" + str(x)

from queue import queue

class taskmgr:

def __init__(self):

self.task_q = queue()

def add(self, task):

self.task_q.put(task)

def run(self):

while not self.task_q.empty():

for i in xrange(self.task_q.qsize()):

try:

gen = self.task_q.get()

print gen.next()

except stopiteration:

print str(i) + "stop."

pass

else:

self.task_q.put(gen)

t = taskmgr()

t.add(tt())

t.add(yy())

t.run()

python函式知識點整理

函式 1.函式是組織好的,可以重複使用的,用來實現單一或相關功能的 段 2.語法 def 函式名 引數列表 函式體return defadd a,b returna b sum add 11,12 print sum 可以返回多個值,返回的多個值組成乙個元組,返回值上加上一對中括號,則返回乙個列表 ...

Python知識點整理

參考 python.doc 廖雪峰的python教程 使用 將兩行 為一行 if 1900 year 2100 and1 month 12 and1 day 31 and0 hour 24 and0 minute 60 and0 second 60 looks ike a valid date re...

python知識點整理

1 python列表和元祖 python包含6中內建的序列,即列表 元組 字串 unicode字串 buffer物件和xrange物件。通用序列操作 索引 分片 序列相加 乘法 成員資格 in 長度 len 最小值 min 和最大值 max 2 python字典 花括號 字典是另一種可變容器模型,且...