子函数的定义


#定义一个子函数,格式是:
#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