日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > python >内容正文

python

详解Python模块化编程-自定义函数

發(fā)布時(shí)間:2024/9/15 python 48 豆豆
生活随笔 收集整理的這篇文章主要介紹了 详解Python模块化编程-自定义函数 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

本文目錄

0、楔子 1、自定義函數(shù)格式 2、編寫(xiě)函數(shù)說(shuō)明文檔 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)入新程序中

正文開(kāi)始啦

0、楔子

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

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

28.274333882308138

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

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

28.274333882308138

348368.06776391855


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

格式如下:

def?fun_name(args):fun_bodyreturn?xxfun_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語(yǔ)句同一行。

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

120


2、編寫(xiě)函數(shù)說(shuō)明文檔

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

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

'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)題化字符,單詞的開(kāi)頭為大寫(xiě),其余為小寫(xiě) des_sb("cao","anhui")

Cao comes from Anhui.

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

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

def?des_sb(name,provice):"""describe?sb"""print("%s?comes?from?%s."%(name.title(),provice.title())) #無(wú)需考慮輸入實(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']?=?firstprofile['last_name']?=?lastfor?key,?value?in?user_info.items():profile[key]?=?valuereturn?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 語(yǔ)句將值返回到調(diào)用函數(shù)的代碼行。

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

將函數(shù)存儲(chǔ)在被稱為模塊的獨(dú)立文件(模塊可以理解為以.py結(jié)尾的文件)中,再將模塊導(dǎo)入到主程序中。import 語(yǔ)句允許在當(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打開(kāi)文件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編程:從入門(mén)到實(shí)踐Python基礎(chǔ)教程(第3版)

END

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

推薦閱讀

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

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

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

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

總結(jié)

以上是生活随笔為你收集整理的详解Python模块化编程-自定义函数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。