子函數的定義


#定義一個子函數,格式是:
#def 函數名(參數1,參數2,'''): 這里有一個冒號不要忘記
#接下來定義一個沒有參數的子函數printHello
def printHello() :
    print("Hello world")

#直接調用函數
printHello()
#定義一個有參數的函數
def printAnimal(animalType,animaName):
    print("My animal is "+animalType.title()+" ans name is "+animaName.title())
printAnimal("hamster","rourou")

上邊的函數參入實參和傳入的位置有關系,接下來使用關鍵字實參就不應考慮傳入參數的位置了

#參入參數和位置沒有關系
def printAnimal(animalType,animaName):
    print("My animal is "+animalType.title()+" ans name is "+animaName.title())
printAnimal(animaName = "rourou",animalType = "hamster")

 

#並非傳入所有的形參
def printName(firstName,midName,lastName):
    if midName:
        print("我有中間名字")
        fullName = firstName + " " + midName + " " + lastName;
    else:
        print("我沒有中間名字")
        fullName = firstName + " " + lastName;
    return fullName

firstName = input("輸入你的第一個名字:")
midName = input("輸入你的中間名字:")
lastName = input("輸入你最后的名字:")
print(printName(firstName,midName,lastName))
#1.
# 輸入你的第一個名字:a
# 輸入你的中間名字:v
# 輸入你最后的名字:s
# 我有中間名字
# a v s
# 2.
# 輸入你的第一個名字:a
# 輸入你的中間名字:
# 輸入你最后的名字:b
# 我沒有中間名字
# a b

 

#一個函數可以返回任何值,包括復雜的字典和列表
def getInfo(name,address,age=''):
    fullName = {
        'name': name,
        'address': address,
    }
    if age:
        fullName['age'] = age
    return fullName

info = getInfo('小怪','北京',age='24')
print(info) #{'name': '小怪', 'address': '北京', 'age': 24}
info = getInfo('小怪','北京')  #{'name': '小怪', 'address': '北京'}
print(info)
#可以向函數傳遞列表
def getUsers(userLst):
    for user in userLst:
        print('Hello '+user.title())
lst = ['xiaoguai','daguai','wangqiang']
getUsers(lst)

# Hello Xiaoguai
# Hello Daguai
# Hello Wangqiang
#實現兩個列表的傳值和打印
def transmitValue(lst1,lst2):
    while lst1 :
        value = lst1.pop()
        lst2.append(value)

def printLst(lst1):
    for value in lst1:
        print(value,end=" ")
    print()

lst1 = ['abc','bcd','cde','def','efg']
lst2 = []
transmitValue(lst1,lst2)
printLst(lst2)   #efg def cde bcd abc 上述的lst1會變成空列表
#我們只是希望去把lst1的內容傳遞到lst2中,並不希望去改變lst1的內容,我們可以這么做
def transmitValue(lst1,lst2):
    while lst1:
        value = lst1.pop()
        lst2.append(value)

def printLst(lst1):
    for value in lst1:
        print(value,end=" ")

lst1 = ['abc','bcd','cde','def','efg']
lst2 = []
transmitValue(lst1[:],lst2)  #這里我們只是傳入了一個lst1的副本,所以這樣就樂意保護真實的lst1不會變成空表
printLst(lst1) #abc bcd cde def efg
print()
printLst(lst2)#efg def cde bcd abc 

*elelment中的*是創建一個名字為element的空元組,並把所有的值都分裝在這個元組中

def printValue(*element):
    for value in element:
        print('-'+value.title())
print('abc','bcd','cde','def') #abc bcd cde def
print('abc','@@@','sdef') #abc @@@ sdef
#使用任意數量的關鍵字實參
#**userInfo編譯器會自動創建一個空字典,字典名字是userInfo
def build_profile(first,last,**userInfo):
    profile = {}
    profile['firstName'] = first
    profile['lastName'] = last
    for key,value in userInfo.items():
        profile[key] = value
    return profile
first = input("輸入你的第一個姓名:")
last = input("輸入你的最后的姓名")
address = input("輸入你的地址")
age = input('輸入你的年齡')
userInfoList = build_profile(first,last,address=address,age=age)#{'firstName': 'xiaoguai', 'lastName': 'daguai', 'address': '北京', 'age': '24'}
print(userInfoList)

將函數存儲在稱為模塊的獨立文件中,再把模塊導入主程序中,import語句就是允許在當前運行的文件中使用模塊中的代碼,通過函數存儲在獨立文件中,可隱藏代碼的細節,把重點放在高層邏輯上,還可以和其他程序員分享這些文件而不是整個代碼,相當於C/C++的頭文件。要讓函數是可導入的,得先創造模板,模板是擴展名為.py的文件,例如:

在template.py中定義如下的函數:

#模板文件
def makePizza(size,*toppings):
    print('Make a '+ str(size)+'-inch Pizza with follow toppings:' )
    for topping in toppings:
        print('- '+ topping)

在主函數中(另外一個.py的文件中):注意關鍵詞import,和template.一個函數,這個函數是在template.py中的,這時候會將所有的template.py內的函數都復制過來

但是你並看不到復制過來的代碼。語法:import 模板名

import template
template.makePizza(16,'pepperoin','green peppers')
template.makePizza(12,'mushroom','extra cheese')
# Make a 16-inch Pizza with follow toppings:
# - pepperoin
# - green peppers
# Make a 12-inch Pizza with follow toppings:
# - mushroom
# - extra cheese

但是有時候我們不需要全部導入,只需要導入部分模板中的函數,就需要用一下的定義方式:

from 模板名 import 函數1,函數2,函數3.......

#模板文件template.py
def makePizza(size,*toppings):
    print('Make a '+ str(size)+'-inch Pizza with follow toppings:' )
    for topping in toppings:
        print('- '+ topping)

def userInfoList(first,last,**personInfo):
    person = {}
    person['first'] = first
    person['last'] = last
    for key,value in personInfo.items():
        person[key] = value
    return person

#function2.py
from template import makePizza,userInfoList  
makePizza(12,'pepperoin','green peppers')
userList = userInfoList('xiaoguai','daguai',address='北京',age = 24)
print(userList)
# - pepperoin
# - green peppers
# {'first': 'xiaoguai', 'last': 'daguai', 'address': '北京', 'age': 24}

有時候模板里的函數和我們主函數內的函數重名或者模板函數天長了,我們可以給這個模板函數起一個別名,語法如下:

from 模板 import 函數名 as 別名

#template.py
def longNamelongName():
    for i in range(1,10):
        for j in range(1,i+1):
            print(j,'*',i,'=',i*j,end="\t")
        print()

#function2.py
from template import longNamelongName as nineList  #給函數longNamelongName起了一個別名nineList
nineList()
# 1 * 1 = 1    
# 1 * 2 = 2    2 * 2 = 4    
# 1 * 3 = 3    2 * 3 = 6    3 * 3 = 9    
# 1 * 4 = 4    2 * 4 = 8    3 * 4 = 12    4 * 4 = 16    
# 1 * 5 = 5    2 * 5 = 10    3 * 5 = 15    4 * 5 = 20    5 * 5 = 25    
# 1 * 6 = 6    2 * 6 = 12    3 * 6 = 18    4 * 6 = 24    5 * 6 = 30    6 * 6 = 36    
# 1 * 7 = 7    2 * 7 = 14    3 * 7 = 21    4 * 7 = 28    5 * 7 = 35    6 * 7 = 42    7 * 7 = 49    
# 1 * 8 = 8    2 * 8 = 16    3 * 8 = 24    4 * 8 = 32    5 * 8 = 40    6 * 8 = 48    7 * 8 = 56    8 * 8 = 64    
# 1 * 9 = 9    2 * 9 = 18    3 * 9 = 27    4 * 9 = 36    5 * 9 = 45    6 * 9 = 54    7 * 9 = 63    8 * 9 = 72    9 * 9 = 81    

當如模板中的所有函數,使用*,例如:from template import *    這句代碼就回吧模板tmeplate中的所有函數復制到主函數中,但是你任然看不到代碼細節,

這就不用在使用點表示法來調用函數了,也就是不用這樣了:template.function()。只需要直接寫出函數名稱就可以使用了,但是有一個問題就出現了,當我們寫的函數和模板中的函數名稱一樣的話就會出現函數名覆蓋的現象,結果也就是無法預測的,所以兩種解決辦法,第一種::我只要導入我需要調用的函數就行了;第二種:我使用點表示法,例如:template.function()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM