1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        詳解Python模塊化編程-自定義函數(shù)

        共 5866字,需瀏覽 12分鐘

         ·

        2022-03-08 14:11

        本文目錄

        0、楔子

        1、自定義函數(shù)格式

        2、編寫函數(shù)說明文檔

        3、函數(shù)參數(shù)

        ? 函數(shù)形參和實(shí)參區(qū)別

        ? 位置實(shí)參

        ? 關(guān)鍵字實(shí)參

        ? 默認(rèn)實(shí)參

        ? 讓實(shí)參可選

        ? 傳遞任意數(shù)量的實(shí)參

        ? 結(jié)合使用位置實(shí)參和任意數(shù)量實(shí)參

        ? 使用任意數(shù)量的關(guān)鍵字實(shí)參


        4、函數(shù)返回值

        ? 將函數(shù)存儲(chǔ)在模塊中并導(dǎo)入新程序中

        正文開始啦0、楔子

        函數(shù)可以理解為多條語句整合而成的代碼塊,指定特定的名稱, 用于實(shí)現(xiàn)具體的功能。函數(shù)可以實(shí)現(xiàn)代碼更好的復(fù)用,是結(jié)構(gòu)化編程的核心。例如,已知圓的半徑r求圓的面積,可以通過如下代碼解決。

        import?math
        r?=?3
        S?=?math.pi*r*r
        print(S)

        28.274333882308138

        但是,當(dāng)需要求多個(gè)圓的面積時(shí),反復(fù)寫上面代碼就顯得很繁瑣,這時(shí)可以定義一個(gè)求圓面積的函數(shù)s_circle,每次只需傳入不同圓的半徑,即可計(jì)算不同圓面積。

        def?s_circle(r):
        ????S?=?math.pi*r*r
        ????return?S
        print(s_circle(3))
        print(s_circle(333))

        28.274333882308138

        348368.06776391855


        1、 自定義函數(shù)格式

        格式如下:

        def?fun_name(args):
        ????fun_body
        ????return?xx

        fun_name,自定義的函數(shù)名;
        args,傳入函數(shù)的參數(shù);
        fun_body,函數(shù)體,即函數(shù)想實(shí)現(xiàn)的功能;
        return?xx,return結(jié)束函數(shù),函數(shù)返回值?xx,不指定則返回None

        舉個(gè)栗子,定義一個(gè)計(jì)算圓面積的函數(shù):

        def?s_circle(r):#自定義函數(shù)s_circle,傳入的參數(shù)r。
        ????S?=?math.pi*r*r#函數(shù)體
        ????return?S????#返回圓的面積S
        print(s_circle(3))#函數(shù)名()調(diào)用函數(shù),括號(hào)內(nèi)為傳入

        28.274333882308138

        當(dāng)函數(shù)體只有一行時(shí),可以置于def語句同一行。

        def?for_multi(x,y):?print(x*y)#函數(shù)定義
        for_multi(10,12)#調(diào)用函數(shù)

        120


        2、編寫函數(shù)說明文檔

        說明文檔置于函數(shù)開頭處,作為函數(shù)的一部分存儲(chǔ)起來,通過函數(shù)名.__doc__可查看說明文檔。

        def?s_circle(r):
        ????"compute?the?circular?area?with?radius"#函數(shù)說明文檔內(nèi)容
        ????S?=?math.pi*r*r
        ????return?S
        s_circle.__doc__#函數(shù)__doc__屬性存儲(chǔ)函數(shù)說明文檔

        'compute the circular area with radius'


        3、函數(shù)參數(shù)

        形參和實(shí)參區(qū)別

        • 形參:定義函數(shù)時(shí),函數(shù)名稱后面括號(hào)里的內(nèi)容為形參;
        • 實(shí)參:調(diào)用函數(shù)時(shí),括號(hào)里的內(nèi)容為實(shí)參。
        def?hello2sb(sb):#括號(hào)內(nèi)為傳入的參數(shù),此處sb為形參。
        ?????print("Hello?%s!"%sb.title())
        hello2sb("jack")?#此處jack為調(diào)用hello2sb的實(shí)參,是調(diào)用函數(shù)時(shí)傳遞給函數(shù)的信息。?

        Hello Jack!

        位置實(shí)參

        調(diào)用函數(shù)時(shí)按照形參的順序關(guān)聯(lián)實(shí)參。

        def?des_sb(name,provice):
        ????"""describe?sb"""
        ????print("%s?comes?from?%s."%(name.title(),provice.title()))
        #title函數(shù)返回標(biāo)題化字符,單詞的開頭為大寫,其余為小寫
        des_sb("cao","anhui")

        Cao comes from Anhui.

        關(guān)鍵字實(shí)參

        形參=實(shí)參傳遞參數(shù),無需考慮實(shí)參順序。

        def?des_sb(name,provice):
        ????"""describe?sb"""
        ????print("%s?comes?from?%s."%(name.title(),provice.title()))
        #無需考慮輸入實(shí)參順序,以下兩種輸出一樣
        des_sb(name?=?"cao",provice?=?"anhui")
        des_sb(provice?=?"anhui",name?=?"cao")#顛倒實(shí)參順序

        Cao comes from Anhui.

        Cao comes from Anhui.

        默認(rèn)實(shí)參

        定義函數(shù)時(shí),給形參一個(gè)默認(rèn)值,調(diào)用函數(shù)時(shí)若提供了實(shí)參則使用提供值,否則使用默認(rèn)值。

        def?des_sb(name,provice,dynasty="Three?Kingdoms?Era"):#定義時(shí)形參dynasty指定默認(rèn)值
        ????"""describe?sb"""
        ????print("%s?comes?from?%s?of?%s."%(name.title(),provice.title(),dynasty))
        des_sb(name?=?"cao",provice?=?"anhui")#形參此處未指定實(shí)參,調(diào)用默認(rèn)值
        des_sb(name?=?"cao",provice?=?"anhui",dynasty?=?"Qin")#dynasty指定實(shí)參,使用實(shí)參

        Cao comes from Anhui of Three Kingdoms Era.

        Cao comes from Anhui of Qin.

        **注意:**以上三種參數(shù)傳遞方式可以混用,自己最容易理解的調(diào)用方式即可。

        讓實(shí)參可選

        指定形參默認(rèn)值為空字符串,放到所有形參最后,則該形參可空(可以提供實(shí)參也可以不用)。

        def?return_fullname(firstname,lastname,middlename=""):
        ????"""Show?fullname"""
        ????if?middlename:
        ????????fullname?=?"?".join((middlename.title()+""+lastname,firstname.title()))
        ????else:
        ????????fullname?=?"?".join((lastname.title(),firstname.title()))
        ????return?fullname#返回fullname
        #調(diào)用函數(shù)
        fullname?=?return_fullname(firstname?=?"cao",lastname?=?"cao")#middlename形參為空
        fullname1?=?return_fullname(firstname?=?"cao",middlename?=?"meng",lastname?=?"de")
        print(fullname)
        print(fullname1)

        Cao Cao

        Mengde Cao

        傳遞任意數(shù)量的實(shí)參

        定義函數(shù)時(shí)使用:*形參名稱。

        def?known_tangera(*heros):#星號(hào)(*)使得Python將所有實(shí)參存入heros元組中
        ????"""show?known?heros?in?tang"""
        ????print(heros)
        known_tangera("yuanba?li","shiming?li")
        known_tangera("yuanba?li","shiming?li","cheng?nuo")

        ('yuba li', 'shiming li')

        ('yuba li', 'shiming li', 'cheng nuo')

        結(jié)合使用位置實(shí)參和任意數(shù)量實(shí)參

        在函數(shù)定義中將接納任意數(shù)量實(shí)參的形參(*形參名)放在最后.。

        def?make_pizza(size,?*toppings):
        ????"""概述要制作的比薩"""
        ????print("\nMaking?a?"?+?str(size)?+?"-inch?pizza?with?the?following?toppings:")
        ????for?topping?in?toppings:#toppings元組存儲(chǔ)任意數(shù)量的實(shí)參
        ????????print("-?"?+?topping)
        make_pizza(16,?'pepperoni')
        make_pizza(12,?'mushrooms',?'green?peppers',?'extra?cheese')

        Making a 16-inch pizza with the following toppings:

        - pepperoni

        Making a 12-inch pizza with the following toppings:

        - mushrooms -

        - green peppers

        - extra cheese

        使用任意數(shù)量的關(guān)鍵字實(shí)參

        定義函數(shù)時(shí)使用:**形參名稱。

        def?build_profile(first,?last,?**user_info):
        ????#形參**user_info?中的兩個(gè)星號(hào)讓Python創(chuàng)建一個(gè)名為user_info?的空字典,?
        ????#并將收到的所有名稱—值對(duì)都封裝到這個(gè)字典中。
        ????"""創(chuàng)建一個(gè)字典,?其中包含我們知道的有關(guān)用戶的一切"""
        ????profile?=?{}
        ????profile['first_name']?=?first
        ????profile['last_name']?=?last
        ????for?key,?value?in?user_info.items():
        ????????profile[key]?=?value
        ????return?profile
        #傳遞
        user_profile?=?build_profile('albert',?'einstein',
        ?????????????????????????????location='princeton',
        ?????????????????????????????field='physics')
        print(user_profile)

        {'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}


        4、函數(shù)返回值

        在函數(shù)中, 可使用return 語句將值返回到調(diào)用函數(shù)的代碼行。

        將函數(shù)存儲(chǔ)在模塊中并導(dǎo)入新程序中

        將函數(shù)存儲(chǔ)在被稱為模塊的獨(dú)立文件(模塊可以理解為以.py結(jié)尾的文件)中,再將模塊導(dǎo)入到主程序中。import 語句允許在當(dāng)前運(yùn)行的程序文件中使用模塊中的代碼。導(dǎo)入模塊的方法有多種, 下面對(duì)每種都作簡(jiǎn)要的介紹

        • 導(dǎo)入整個(gè)模塊

        下面創(chuàng)建pizza模塊,pizza.py:

        def?make_pizza(size,?*toppings):
        ????"""概述要制作的比薩"""
        ????print("\nMaking?a?"?+?str(size)?+
        ??????????"-inch?pizza?with?the?following?toppings:")
        ????for?topping?in?toppings:
        ????????print("-?"?+?topping)
        • 在pizza.py所在的目錄中創(chuàng)建另一個(gè)名為making_pizzas.py的模塊:
        import?pizza#導(dǎo)入pizza模塊
        #讓Python打開文件pizza.py,并將其中的所有函數(shù)都復(fù)制到這個(gè)程序中。
        #本程序可以使用pizza.py中定義的所有函數(shù)。
        pizza.make_pizza(16,?'pepperoni')#調(diào)用pizza模塊中make_pizza函數(shù)
        pizza.make_pizza(12,?'mushrooms',?'green?peppers',?'extra?cheese')

        Making a 16-inch pizza with the following toppings:

        - pepperoni

        Making a 12-inch pizza with the following toppings:

        - mushrooms

        - green peppers

        - extra cheese

        • 導(dǎo)入模塊特定的函數(shù)

        #從module_name模塊中導(dǎo)入任意數(shù)量函數(shù),函數(shù)之間逗號(hào)分割。

        from module_name import function_0, function_1, function_2

        making_pizzas.py

        from?pizza?import?make_pizza#只導(dǎo)入pizza模塊中的make_pizza函數(shù)
        make_pizza(16,?'pepperoni')#調(diào)用pizza模塊中make_pizza函數(shù)
        make_pizza(12,?'mushrooms',?'green?peppers',?'extra?cheese')
        • 導(dǎo)入模塊中的所有函數(shù)

        使用星號(hào)(* ) 運(yùn)算符可讓Python導(dǎo)入模塊中的所有函數(shù)。

        from?pizza?import?*#導(dǎo)入pizza模塊所有函數(shù)
        make_pizza(16,?'pepperoni')
        make_pizza(12,?'mushrooms',?'green?peppers',?'extra?cheese')
        • 使用as 給函數(shù)指定別名
        from?pizza?import?make_pizza?as?mp#函數(shù)別名mp
        mp(16,?'pepperoni')
        mp(12,?'mushrooms',?'green?peppers',?'extra?cheese')
        • 使用as 給模塊指定別名
        import?pizza?as?p#模塊別名p
        p.make_pizza(16,?'pepperoni')
        p.make_pizza(12,?'mushrooms',?'green?peppers',?'extra?cheese'

        參考:Python編程:從入門到實(shí)踐Python基礎(chǔ)教程(第3版)

        END


        各位伙伴們好,詹帥本帥搭建了一個(gè)個(gè)人博客和小程序,匯集各種干貨和資源,也方便大家閱讀,感興趣的小伙伴請(qǐng)移步小程序體驗(yàn)一下哦!(歡迎提建議)

        推薦閱讀


        牛逼!Python常用數(shù)據(jù)類型的基本操作(長文系列第①篇)

        牛逼!Python的判斷、循環(huán)和各種表達(dá)式(長文系列第②篇)

        牛逼!Python函數(shù)和文件操作(長文系列第③篇)

        牛逼!Python錯(cuò)誤、異常和模塊(長文系列第④篇)


        瀏覽 61
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
        評(píng)論
        圖片
        表情
        推薦
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            天天插天天狠 | 骚逼国产 | 51av视频 | 欧美第一作坊视频平台2020欧美 | 欧美一区二区三区在线 | 久久夜色视频 | 男女做视频网站免费观看 | 男生操女生小视频 | 青娱乐成人免费在线视频 | 久久久久网精品影视一起草 |