1. 程式人生 > >《Python程式設計從入門到實踐》第8章 函式

《Python程式設計從入門到實踐》第8章 函式

第8章 函式

只記錄了自己以前沒有注意到的知識點

一、傳遞實參

​ 向函式傳遞實參的方式有很多種,可以使用位置實參,這要求實參的順序和形參的順序相同;也可以使用關鍵字實參,其中的每個實參都是由變數名和實參組成,還可以使用字典和列表

1. 位置實參

​ 基於實參的順序進行關聯

def describe_pet(animal_type, pet_name):
	"""顯示寵物的資訊"""      
	print("\nI have a " + animal_type + ".")      
    print("My " + animal_type + "'s name is " + pet_name.
title() + ".") describe_pet('hamster', 'harry') # 按順序對應起來,我覺得是最普遍的用法了 #輸出 I have a hamster. My hamster's name is Harry

2.關鍵字實參

​ 關鍵字實參是傳遞給函式的名稱—值對。

def describe_pet(animal_type, pet_name):
	"""顯示寵物的資訊"""      
	print("\nI have a " + animal_type + ".")      
    print("My " + animal_type + "'s name is "
+ pet_name.title() + ".") describe_pet(animal_type='hamster',pet_name='harry') describe_pet(pet_name="jkljkl",animal_type='dog') #輸出 I have a hamster. My hamster's name is Harry. I have a dog. My dog's name is Jkljkl.

​ 在傳遞實參的時候,把它要傳遞給的形參直接寫出來

3.預設值

​ 編寫函式時,可給每個形參指定預設值。在呼叫函式中給形參提供了實參,Python將使用指定的實參;否則,將使用形參的預設值。

使用預設值的時候,在形參列表中必須先列出沒有預設值的列表,再列出有預設值的形參。

二、傳遞列表

​ 將列表傳遞給函式之後,函式就可以對列表進行修改,再函式中對列表所作的修改是永久性的

example = list(range(1, 10))  # 生成一個列表
print('before:', example)


def deal(example_list):
    while example_list:  # 刪除列表中的所有元素
        example_list.pop()


deal(example)
print('after:', example)  # 輸出列表

#輸出
before: [1, 2, 3, 4, 5, 6, 7, 8, 9]
after: []

​ 可見列表在函式中做了修改

​ 那麼怎麼樣才能不修改原來的列表----->建立副本 list[:],缺點:需要花費時間和記憶體去建立記憶體

example = list(range(1, 10))  # 生成一個列表
print('before:', example)


def deal(example_list):
    while example_list:  # 刪除列表中的所有元素
        example_list.pop()


deal(example[:])#建立了副本
print('after:', example)  # 輸出列表

#輸出
before: [1, 2, 3, 4, 5, 6, 7, 8, 9]
after: [1, 2, 3, 4, 5, 6, 7, 8, 9]

三、傳遞任意數量的實參

​ 有時候,你預先不知道函式需要接受多少個實參,好在Python允許從呼叫語句中手機任意數量的實參

​ 看個例子

def make_pizza(*toppings):    
    """列印顧客點的所有配料"""    
    print(toppings) 
    
make_pizza('pepperoni') 
make_pizza('mushrooms', 'green peppers', 'extra cheese')

#輸出
('pepperoni',) 
('mushrooms', 'green peppers', 'extra cheese')

​ 形參名 *toppings 中的星號讓Python建立一個名為 toppings 的空元組,並將收到的所有值都封裝這個元組裡

#### 	1.結合使用位置實參和任意數量實參

​ 如果要讓函式接受不同型別的實參,必須在函式定義中將接納任意數量實參的形參放在最後

def make_pizza(size, *toppings):    
    """概述要製作的比薩"""    
    print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")    
    for topping in toppings:        
        print("- " + topping) 
        
 make_pizza(16, 'pepperoni') 
 make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

#輸出
Making a pizza with the following toppings: 
- pepperoni 

Making a pizza with the following toppings: 
- mushrooms 
- green peppers 
- extra cheese

2.使用任意數量的關鍵字實參

​ 有時候,需要接受任意數量的實參,但是預先不知道傳遞給函式的會是什麼樣的資訊,在這種情況下,可將函式編寫成能夠接受任意數量的鍵值對

def build_profile(first, last, **user_info):      
        """建立一個字典,其中包含我們知道的有關使用者的一切"""      
	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',ield='physics')  
print(user_profile)

​ 形參**user_info 中的兩個星號讓Python建立一個名為user_info 的 空字典,並將收到的所有名稱—值對都封裝到這個字典中。

四、將函式儲存在模組中

​ 1.匯入整個模組

import pizza #最普遍的方法

​ 2.匯入特定的函式

from pizza import make_pizza #無需使用句點

​ 3.使用 as 給函式指定別名

from pizza import make_pizza as mp #解決有重名的問題,或者函式名太長

​ 4.使用 as 給模組指定別名

import pizza as p #指定簡短的別名,更好的呼叫模組中的函式

​ 5.匯入模組中的所有函式

from pizza import * #可通過名稱來呼叫函式,而無需使用句點表示法