1. 程式人生 > >python 入門第三課 函式function

python 入門第三課 函式function

1、函式定義: 函式是指將一組語句的集合通過一個名字(函式名)封裝起來,要想執行這個函式,只需呼叫其函式名即可
特性:
減少重複程式碼
使程式變的可擴充套件
使程式變得易維護

函式呼叫時,位置引數必須提供,預設引數可以不輸入,介於位置引數後面,對於不確定個數的位置引數,函式定義時可以使用args,將多個不確定的位置引數轉換為元組形式的引數,函式呼叫時也可以使用[]方式,對於多個不確定個數的關鍵字引數,函式定義時可以使用**kwargs,將多個不確定的關鍵字引數轉換為字典形式的引數,函式呼叫時也可以使用{key:value}方式,

__author__ = 'admin'
def test(x,y=2,*args,**kwargs):
    print(x)
    print(y)
    print(args)
    print(kwargs)

test(2)
test(2,5,8,9,12)
test(2,5,*[8,9,12])
test(2,5,*[8,9,12],name = 'chongmao',age = 23)
test(2,5,*[8,9,12],**{'name':  'alex','age':  20})

最後一行輸出:
2
5
(8, 9, 12)
{'name': 'alex', 'age': 20}

2、遞迴:函式內部呼叫自己

遞迴特性:

  1. 必須有一個明確的結束條件
  2. 每次進入更深一層遞迴時,問題規模相比上次遞迴都應有所減少
  3. 遞迴效率不高,遞迴層次過多會導致棧溢位
__author__ = 'admin'

def calc(n):
    print(n)
    if int (n/2)>0 :
        return calc(int(n/2))
    print('---->:',n)

calc(10)

3、配置檔案的資訊計數1、查詢資訊2、增加寫入3、刪除資訊4
配置檔案寫於‘TEXTpy2’中,待寫入或刪除的內容 讀取於字典arg中。choice ==1,讀取 行以backend開始的行數,計數;choice ==2,提示輸入一個網址如‘www.oldboy5.org’,以列表的方式讀取檔案內容,判斷輸入的內容是否在列表的元素中,如果在,則輸出下一行即列表下一個元素的的詳細資訊;choice ==3,分兩行寫入字典arg中的內容,以格式化的方式寫入TEXTpy2的文末;choice ==4,readlines()以列表方式讀取所有內容,過濾掉待刪除的內容,重新寫入新檔案。
初始TEXTpy2檔案如下:
frontend oldboy.org
bind 0.0.0.0:80
option httplog
option httpclose
option forwardfor
log global
acl www hdr_reg(host) -i www.oldboy.org
use_backend www.oldboy.org if www

backend www.oldboy.org
server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000

backend www.oldboy5.org
server 100.1.7.9 100.1.7.11 weight 20 maxconn 300

backend www.oldboy7.org
server 100.1.7.9 100.1.7.7 weight 20 maxconn 3000

backend www.oldboy8.org
server 100.1.7.8 weight 20 maxconn 30

__author__ = 'admin'

arg = {
            'backend': 'www.oldboy6.org',
            'record':{
                'server': '100.1.7.8',
                'weight': 20,
                'maxconn': 30
            }
        }
choice = input('input a number : 1 for count,2 for search,3 for new write,4 for delete:')

if choice =='1':
    with open('TEXTpy2','r',encoding='utf-8') as fcount :
        count = 0
        for line in fcount:
            # fline = fcount.readline()
            if fcount.readline().startswith('backend '):
                print(fcount.readline().strip())
                count+=1
        print(count)

elif choice =='2':
    f_input = input('please input a website:')
    f_in_line = 'backend '+f_input+'\n'
    print(f_in_line)
    with open('TEXTpy2','r',encoding='utf-8') as fsearch :
        lines = fsearch.readlines()
        for i in range(len(lines)):
            if f_in_line in lines[i] :
                print('The detail information is:',lines[i+1].strip())

elif choice =='3':
    f_w = '\nbackend '+arg['backend']
    f_w_info = '        server '+arg['record']['server']+' weight %s maxconn %s'%(arg['record']['weight'],arg['record']['maxconn'])
    with open('TEXTpy2','r+',encoding='utf-8') as f_write :
        if f_w.strip()+'\n' in f_write :
            print('The web exists')
        else:
            f_write.write('\n')
            f_write.write(f_w)
            f_write.write('\n')
            f_write.write(f_w_info)
            f_write.seek(0)
            print(f_write.readlines())

elif choice =='4':
    f_w = 'backend '+arg['backend']+'\n'
    f_w_info = '        server '+arg['record']['server']+' weight %s maxconn %s'%(arg['record']['weight'],arg['record']['maxconn'])
    with open('TEXTpy2','r',encoding='utf-8') as f_r :
        lines = f_r.readlines()
        print(lines)
    with open('TEXTpy2','w',encoding='utf-8') as f_rewrite :
        index_del = lines.index(f_w)
        print(index_del)
        del lines[index_del:index_del+3]
        for i in range(len(lines)):
            f_rewrite.write(lines[i])

else:
   print('Invalid input.')

4、函式即變數:
4.1.1 高階函式:
4.1.1a、 將函式名作為形參傳給另一個函式(在不修改被裝飾函式原始碼的情況下為其新增功能)

__author__ = 'Administrator'
import time
def bar():
    time.sleep(3)
    print('in the bar')

def test(func):
    start_time = time.time()
    func()
    end_time = time.time()
    print('the func run time is%s'%(end_time-start_time))

test(bar)

4.1.1b、返回值中包含函式名(不修改函式的呼叫方式)
巢狀函式:

def foo():
    print('in the foo')
    def bar():
        print('in the bar')
    bar()
foo()

4.1.2高階函式+巢狀函式=》裝飾器

__author__ = 'Administrator'
import time

def timer(func):
    def deco(*args,**kwargs):
        start_time = time.time()
        func(*args,**kwargs)
        end_time = time.time()
        print('the func run time is %s'%(end_time-start_time))
    return deco
@timer
def bar():
    time.sleep(3)
    print('in the bar')
@timer
def test2(name,age):
    time.sleep(1)
    print('info is:',name,age)
bar()
test2('alex',20)

4.2 裝飾器的複合應用
對不同的函式增加差異化的裝飾變數,需要在裝飾函式的外圍增加一層函式,並增加一層返回。

__author__ = 'Administrator'
user,password = 'alex','abc123'
def auth(auth_type):
    def out_wrapper(func):
        def wrapper(*args,**kwargs):
            if auth_type == 'local':
                username = input('username:').strip()
                password1 = input('password:').strip()
                if user ==username and password == password1 :
                    return func(*args,**kwargs)
                else:
                    exit()
            elif auth_type == 'ldap':
                print('Other way...')
        return wrapper
    return out_wrapper
def index():
    print('welcome to index page.')
@auth(auth_type = 'local')
def home():
    print('welcome to home page.')
    return 'from home'
@auth(auth_type = 'ldap')
def bbs():
    print('welcome to bbs page.')

index()
print(home())
bbs()

執行結果示例:

5、 yield生成器.__next__()和.send()使用

__author__ = 'Administrator'
import time
def consumer(name):
    print('%s prepare to eat.'%name)
    while True:
        baozi = yield
        print('baozi %s is coming ,%s will eat it'%(baozi,name))
# c = consumer('wang')
# c.__next__()
# c.__next__()
# c.__next__()
# c.send('pork')
def producer():
    c1 = consumer('A')
    c2 = consumer('B')
    c1.__next__()
    c2.__next__()
    print('Start to make baozi')
    for i in range(1,4,1):
        time.sleep(1)
        print('baozi%s is ok'%i)
        c1.send(i)
        c2.send(i)
producer()

6、try--except和yield生成斐波那契數列:

def fib(max):
    n,a,b=0,0,1
    while n <max :
#        print(b)
        yield b
        a,b = b,a+b
        n +=1
    return  '--done--'

g = fib(10)

while True:
    try :
        x = next(g)
        print('g:',x)
    except StopIteration as e:
        print('generator return value',e.value)
        break