Python函數的冒泡排序、遞迴以及裝飾器

來源:互聯網
上載者:User

標籤:調用   修改   遞迴函式   傳回值   冒泡排序   **kwargs   應用   目的   class   

函數的冒泡排序:

本質是,讓元素換位置,逐個比較最終排序。

例1:實現a1,a2值互換:

a1 = 123a2 = 456temp = a1a1 = a2a2 = tempprint(a1)print(a2)結果:456123

冒泡排序:

#!/bin/bash/env python# -*- coding:utf-8 -*-li =  [22,1,5,4,3,66,22,12,34,21]for j in range(1,len(li)):    for i in range(len(li)-1):        if li[i] > li[i+1]:            temp = li[i]            li[i] = li[i+1]            li[i+1] = tempprint(li)結果:[1, 3, 4, 5, 12, 21, 22, 22, 34, 66]

 

遞迴:

在函數內部可以調用其他函數。如果一個函數在內部調用自己,這個函數就是遞迴函式。

例:

#!/bin/bash/env pythondef f4(a1,a2):    if a1 > 10000:        return    print(a1)    a3 = a1 + a2    f4(a2,a3)f4(0,1)結果:011235813213455891442333776109871597258441816765

 

函數裝飾器:

裝飾器的目的:當要修改一段代碼時,而不進行內部的修改,這就需要在外部加裝飾器來達到效果。

原函數執行之前進行的操作:

#!/bin/bash/env pythondef outer(func):    def inner():        print(‘hello‘)        print(‘let is‘)        print(‘moumou‘)        r = func()        return r    return inner@outerdef func1():    print(‘yes‘)func1()結果:hellolet ismoumouyes

函數執行之後進行操作:

def outer(func):    def inner():        r = func()        print(‘hello‘)        print(‘let is‘)        print(‘moumou‘)        return r    return inner@outerdef func1():    print(‘yes‘)func1()結果:yeshellolet ismoumou

@的功能:先執行outer函數,然後把發f1當做參數傳給oute。, 將outer的傳回值重新賦值給f1,所以f1的函數就等於inner()

只要函數應用裝飾器,那麼函數就被重新定義,重新定義為:裝飾器的內層函數。

多個參數裝飾器傳遞:

#!/bin/bash/env pythondef outer(func):    def inner(*args,**kwargs):        print(args)        print(kwargs)        ret = func(*args,**kwargs)        return ret    return inner@outerdef func1(a1,a2,a3):    print("yes")    return a1 + a2 +a3func1(11,22,33)結果:(11, 22, 33){}yes

多個裝飾器的應用:

#!/bin/bash/env pythondef outer(func):    def inner(*args,**kwargs):        print(‘cai‘)        ret = func(*args,**kwargs)        print(‘rui‘)        return ret    return innerdef outer1(func):    def inner1(*args,**kwargs):        print(‘123‘)        ret = func(*args,**kwargs)        return ret    return inner1@outer1@outerdef func1(a1,a2,a3):    print("yes")func1(11,22,33)結果:123caiyesrui

分析:

  

先把outer和func1看做一個整體,把inner放在outer1中執行,然後再執行下面的

 

Python函數的冒泡排序、遞迴以及裝飾器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.