首页 分享 小菜鸟的python学习之路(7)

小菜鸟的python学习之路(7)

来源:萌宠菠菠乐园 时间:2024-12-05 20:49

学习阶梯

《Python编程:从入门到实践》 第一部分:基础知识 第8章 函数

函数是带名字的代码块,用于完成具体的工作。

定义函数

greeter.py

def greet_user(): """显示简单的问候语""" print("Hello!") greet_user() 12345

函数定义关键字是def, 定义以冒号结尾

紧跟的冒号后的所有 缩进行 构成了函数体

“”"括起来的是文档字符串的注释,描述了函数是做什么的,python可以用他们来生成有关程序中函数的文档。

调用函数,指定函数名及其括号内的必要信息即可,作用是让python执行函数内的代码。

向函数传递信息

可在函数定义的括号内添加变量名,添加变量名可让函数接受给这个变量名指定的任何值。

def greet_user(username): """显示简单问候语""" print("Hello, "+username.title()+"!") greet_user('jesse') 12345 实参和形参

形参:在函数定义中,函数()内的变量名是形参,是函数完成其工作所需的一项信息

实参:在调用函数时,括号内的值’jesse’就是一个实参,实参是调用函数时传递给函数的参数

举个栗子:简单来说,就是有个会场,会场内的某个座位被我们贴上了“特殊嘉宾”,这个座位就是专门给特殊嘉宾做的,谁是特殊嘉宾呢? 任何人只要被你允许做到那个座位上,那这个人就是特殊嘉宾。
这里 “特殊嘉宾” 就是函数定义的变量名,“被允许做到那个位置上的人”就是你调用函数时传递的参数,也就是实际的参数,实参。

练习

#8-1 消息:编写一个名为 display_message()的函数,它打印一个句子,指出你在本章学的是什么。调用这个函数,确认显示的消息正确无误。 def display_message(): print("nYou learn about functions in this chapter.") display_message() 1234

#8-2 喜欢的图书:编写一个名为 favorite_book()的函数,其中包含一个名为 title的形参。这个函数打印一条消息,如 One of my favorite books is Alice in Wonderland。调用这个函数,并将一本图书的名称作为实参传递给它。 def favorite_book(title): print("One of my favorite books is "+title) favorite_book('Alice in Wonderland') 1234 传递实参

函数定义中可能包含多个形参,因此函数调用中也可能包含多个实参。

位置实参:要求实参的顺序和形参的顺序相同;

关键字实参:每个实参都由变量名和值组成;

还可使用列表和字典;

位置实参

可根据需要调用函数任意次

调用函数多次是一种效率极高的工作方式

根据需要使用任意数量的位置实参

位置实参的顺序很重要

pets.py

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') #调用函数多次 describe_pet('dog','willie') #位置实参的顺序很重要 describe_pet('willie','dog') 123456789 关键字实参

关键字实参是传递给函数的名称-值对

无需考虑调用中的实参顺序,还清楚地指出函数调用中各个值的用途

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') 1234567

关键字实参的顺序无关紧要,因为python知道各个值该存储到哪个形参中。

默认值

编写函数时,可给每个形参指定默认值。

给形参提供了实参时,python将使用指定的实参值;否则,将使用形参的默认值

给形参指定默认值后,可在函数调用中省略相应的实参。

def describe_pet(pet_name,animal_type='dog'): """显示宠物的信息""" print("nI have a " + animal_type + ".") print("My " + animal_type + "'s name is " + pet_name.title() + ".") describe_pet(pet_name='wille') 12345

在这个函数的定义中,修改了形参的排列顺序

因为一个形参被指定了默认值,,无需实参指定动物类型。

等效的函数调用

由于可混合使用位置实、关键字实参和默认值,通常有多种等效的函数调用方式

def describe_pet(pet_name,animal_type='dog'): print("My " + animal_type + "'s name is " + pet_name.title() + ".") #一条名为willie的小狗 describe_pet('willie') describe_pet(pet_name='willie') #一只名为Harry的仓鼠 describe_pet('harry','hamster') describe_pet(pet_name='harry',animal_type='hamster') describe_pet(animal_type='hamster',pet_name='harry') 1234567891011 避免实参错误

提供的实参多于或少于函数完成其工作所需的信息时,将出现实参不匹配错误。

#这里程序会报错,调用函数没有指定任何实参 def describe_pet(pet_name,animal_type='dog'): print("My " + animal_type + "'s name is " + pet_name.title() + ".") describe_pet() 12345

练习

#8-3 T 恤:编写一个名为 make_shirt()的函数,它接受一个尺码以及要印到 T 恤上的字样。这个函数应打印一个句子,概要地说明 T 恤的尺码和字样。使用位置实参调用这个函数来制作一件 T 恤;再使用关键字实参来调用这个函数。 def make_shirt(size,words): print("The size of this T-shirt is "+size+" and the words are "+words+".") make_shirt(size='L',words='made in China') 1234

#8-4 大号 T 恤:修改函数 make_shirt(),使其在默认情况下制作一件印有字样“I love Python”的大号 T 恤。调用这个函数来制作如下 T 恤:一件印有默认字样的大号 T 恤、一件印有默认字样的中号 T 恤和一件印有其他字样的 T 恤(尺码无关紧要)。 def make_shirt(size='大号',words='I love Python'): print("nT-shirt:") print("tsize: "+size) print("twords: "+words) make_shirt() make_shirt(size='中号') make_shirt(words='其它字样') make_shirt(size='小号',words='else') 123456789

#8-5 城市:编写一个名为 describe_city()的函数,它接受一座城市的名字以及该城市所属的国家。这个函数应打印一个简单的句子,如 Reykjavik is in Iceland。给用于存储国家的形参指定默认值。为三座不同的城市调用这个函数,且其中至少有一座城市不属于默认国家。 def describe_city(city_name,city_country='Iceland'): print(city_name.title()+" is in "+city_country.title()+".") describe_city(city_name='reykjavik') describe_city(city_name='reykjavik', city_country='sydney') describe_city(city_name='london',city_country='england') 123456 返回值

函数并非总是直接显示输出,可以处理一些数据,并返回一个或一组值。

可使用return语句将值返回到调用函数的代码行

返回简单值

formatted_name.py

def get_formatted_name(first_name,last_name): """返回整洁的姓名""" full_name = first_name+' '+last_name return full_name.title() musician=get_formatted_name('jimi','hendrix') print(musician) 123456

函数返回结果到函数调用行

调用返回值的函数时,需要提供一个变量,用于存储返回的值

让实参变成可选的

#改变前 def get_formatted_name(first_name,middle_name,last_name): """返回整洁的姓名""" full_name =first_name+' '+middle_name+' '+last_name return full_name.title() musician=get_formatted_name('john','lee','hooker') print(musician) 12345678

#改变后 def get_formatted_name(first_name, last_name, middle_name=''): """返回整洁的姓名""" if middle_name: full_name=first_name+' '+middle_name + ' ' + last_name else: full_name = first_name + ' ' + last_name return full_name.title() musican=get_formatted_name('jimi','hendrix') print(musican) musician = get_formatted_name('john','hooker','lee') print(musician) 12345678910111213 返回字典

函数可返回任何类型的值,包括列表和字典等较复杂的数据结构。

person.py

def build_person(first_name, last_name): """返回一个字典,其中包含有关一个人的信息""" person = {'first': first_name, 'last': last_name} return person musician = build_person('jimi', 'hendrix') print(musician) 1234567 结合使用函数和while循环

def get_formatted_name(first_name, last_name): """返回整洁的姓名""" full_name = first_name + ' ' + last_name return full_name.title() #这是一个无限循环! ''' while True: print("nPlease tell me your name: ") f_name=input("First name: ") l_name=input("Last name: ") formatted_name=get_formatted_name(f_name,l_name) print("nHello, "+formatted_name+"!") ''' #更改无限循环 while True: print("nPlease tell me your name: ") print("(Enter 'q' at any time to quit)") f_name = input("First name: ") if f_name == 'q': break l_name = input("Last name: ") if l_name == 'q': break formatted_name = get_formatted_name(f_name, l_name) print("nHello, " + formatted_name + "!")

1234567891011121314151617181920212223242526272829

练习

#8-6 城市名:编写一个名为 city_country()的函数,它接受城市的名称及其所属的国家。这个函数应返回一个格式类似于下面这样的字符串:"Santiago, Chile" ,至少使用三个 城市-国家对 调用这个函数,并打印它返回的值。 def city_country(city_name,city_country): print(city_name.title()+" , "+city_country.title()) city_country('santiage','chile') city_country('sydney','australia') city_country('london','britain') 1234567

#8-7 专辑:编写一个名为 make_album()的函数,它创建一个描述音乐专辑的字典。这个函数应接受歌手的名字和专辑名,并返回一个包含这两项信息的字典。使用这个函数创建三个表示不同专辑的字典,并打印每个返回的值,以核实字典正确地存储了专辑的信息。给函数 make_album()添加一个可选形参,以便能够存储专辑包含的歌曲数。如果调用这个函数时指定了歌曲数,就将这个值添加到表示专辑的字典中。调用这个函数,并至少在一次调用中指定专辑包含的歌曲数。 def make_album(singer_name,album_name,sings_number=''): albums={ 'singer name':singer_name.title(), 'album name':album_name.title(), } if sings_number: albums['sings_number']=sings_number return albums album=make_album('marry','love',6) album1=make_album('jade','light') print(album) print(album1) 12345678910111213

#8-8 用户的专辑:在为完成练习 8-7 编写的程序中,编写一个 while 循环,让用户输入一个专辑的歌手和名称。获取这些信息后,使用它们来调用函数 make_album(),并将创建的字典打印出来。在这个 while 循环中,务必要提供退出途径。 def make_album(singer_name, album_name): albums = { 'singer_name': singer_name.title(), 'album_name': album_name.title(), } message = print("nThe album name is " + albums['album_name'] + " and singer name is " + albums['singer_name'] + ".") return message active = True while active: message1 = "n(Enter 'quit' to finish this input.)" message1 += "nPlease enter name of one album: t" album_name = input(message1) if album_name == 'quit': break message2 = "nPlease enter singer name of this album: t" singer_name = input(message2) if singer_name == 'quit': break make_album(singer_name, album_name)

12345678910111213141516171819202122 传递列表

向函数传递列表很有用,这种列表包含的可能是名字、数字或更复杂的对象(如字典)。将列表传递给函数后,函数就能直接访问其内容。

greet_users.py

def greet_users(names): """向列表中的每位用户都发出简单的问候""" for name in names: msg="Hello, "+name.title()+"!" print(msg) usernames=['hannah','try','margot'] greet_users(usernames) 12345678 在函数中修改列表

将列表传递给函数后,函数就可对其进行修改。在函数中对这个列表所做的任何修改都是永久性的,这让你能够高效地处理大量的数据。

printing_models.py

#不使用函数 #首先创建一个列表,其中包含一些要打印的设计 unprinted_designs=['iphone case','robot pendant','dodecahedron'] completed_models=[] #模拟打印每个设计,直到没有未打印的设计为止 # 打印每个设计后,都将其移到列表completed_models中 while unprinted_designs: current_design=unprinted_designs.pop() #模拟根据设计制作的3D打印模型的过程 print("Printing model: "+current_design) completed_models.append(current_design) #显示打印好的所有模型 print("nThe following models have been printed: ") for complete_model in completed_models: print(complete_model)

123456789101112131415161718

为了重新组织这些代码,提高效率。第一个函数将负责处理打印设计的工作,而第二个将概述打印了哪些设计。

#使用函数 #第一个函数负责处理打印设计的工作,第二个概述打印了哪些设计 def print_models(unprinted_designs, completed_models): """ 模拟打印每个设计,直到没有来打印的设计为止 打印每个设计后,都将其移到列表completed_models中 """ while unprinted_designs: current_design = unprinted_designs.pop() #模拟根据设计制作3D打印模型的过程 print("Printing model: " + current_design) completed_models.append(current_design) def show_completed_models(completed_models): """ 显示打印好的所有模型 """ print("nThe following models have been printed: ") for completed_model in completed_models: print(completed_model) unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron'] completed_models = [] print_models(unprinted_designs, completed_models) show_completed_models(completed_models)

123456789101112131415161718192021222324252627

程序演示了一种理念,即每个函数都应只负责一项具体的工作。

禁止函数修改列表

有时候,需要禁止函数修改列表,为了保留原来的文件以供备案,为了解决这个问题,可向函数传递列表的副本而不是原件;这样函数所做的任何修改都只影响副本,而丝毫不影响原件。

function_name(list_name[:]) 1

切片表示法[:]创建列表的副本。

print_models(unprinted_designs[:],completed_models) 1

虽然向函数传递列表的副本可保留原始列表的内容,但除非有充分的理由需要传递副本,否则还是应该讲原始列表传递给函数,因为让函数使用现成列表可避免花时间和内存创建副本,从而提高效率,在处理大型列表时尤其如此。

练习

# 8-9 魔术师:创建一个包含魔术师名字的列表,并将其传递给一个名为show_magicians()的函数,这个函数打印列表中每个魔术师的名字。 magicians=['jack','John','peter'] def show_magicians(magician_name): print("nMagicians as follows: ") for magician in magicians: print("t"+magician) show_magicians(magicians) 12345678

# 8-10 了不起的魔术师:在你为完成练习 8-9 而编写的程序中,编写一个名为make_great()的函数,对魔术师列表进行修改,在每个魔术师的名字中都加入字样“the Great”。调用函数 show_magicians(),确认魔术师列表确实变了。 magicians = ['jack', 'John', 'peter'] def make_great(name): for name in magicians: name = 'the Great ' + str(name) for i in range(3): magicians[i] = name return magicians def show_magicians(magician_name): print("nMagicians as follows: ") for magician in magician_name: print("t" + magician) make_great(magicians) show_magicians(magicians)

123456789101112131415161718

# 8-11 不变的魔术师:修改你为完成练习 8-10 而编写的程序,在调用函数make_great()时,向它传递魔术师列表的副本。由于不想修改原始列表,请返回修改后的列表,并将其存储到另一个列表中。分别使用这两个列表来调用 show_magicians(),确认一个列表包含的是原来的魔术师名字,而另一个列表包含的是添加了字样“the Great”的魔术师名字。 magicians = ['jack', 'John', 'peter'] current_magicians=[] def make_great(magicians): for name in magicians: name='the Great '+str(name) current_magicians.append(name) return current_magicians def show_magicians(magician_name): for magician in magician_name: print("t" + magician) make_great(magicians[:]) print("nbefore magicians as follows: ") show_magicians(magicians) print("nafter magicians as follows: ") show_magicians(current_magicians)

12345678910111213141516171819 传递任意数量的实参

有时候,预先不知道函数需要接受多少个实参,好在python允许函数从调用语句中收集任意数量的实参。

pizza.py

def make_pizza(*toppings): """ 打印顾客点的所有配料 """ print(toppings) make_pizza('pepperoni') make_pizza('mushrooms','green peppers','extra cheese') 123456

形参名*toppings中的*号让python创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中

#将print语句替换为一个循环,对配料列表进行遍历,并对顾客点的比萨进行描述 def make_pizza(*toppings): """ 概述要制作的pizza """ print("nMaking a pizza with the following toppings:") for topping in toppings: print("- "+topping) make_pizza('pepperoni') make_pizza('mushrooms','green peppers','extra cheese') 123456789 结合使用位置实参和任意数量实参

如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。

python线匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中。

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') 12345678 使用任意数量的关键字实参

有时候,需要接受任意数量的实参,但预先不知道传递给函数的会是什么样的信息

可将函数编写成能够接受任意数量的键-值对–调用语句提供了多少就接受多少

user_profile.py

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',field='physics') print(user_profile) 12345678910

形参**user_info中的两个*让python创建一个名为user_info的空字典,并将收到的所有名称-值对都封装到这个字典中

编写函数时,你可以以任何方式混合使用位置实参、关键字实参和任意数量的实参

练习

#8-12 三明治:编写一个函数,它接受顾客要在三明治中添加的一系列食材。这个函数只有一个形参(它收集函数调用中提供的所有食材),并打印一条消息,对顾客点的三明治进行概述。调用这个函数三次,每次都提供不同数量的实参。 def make_sandwichs(*toppings): print("nMaking a sandwich with the following toppings:") for topping in toppings: print("t"+topping) make_sandwichs('pepperoni') make_sandwichs('strawberry jam','romaine lettuce') make_sandwichs('mushrooms','green peppers','extra cheese') 123456789

#8-13 用户简介:复制前面的程序 user_profile.py,在其中调用 build_profile()来创建有关你的简介;调用这个函数时,指定你的名和姓,以及三个描述你的键-值对。 def build_profile(first, last, **user_info): """ 创建一个字典,其中包含我们知道的有关用户的一切 """ profile = {} profile['first_name'] = first.title() profile['last_name'] = last.title() for key, value in user_info.items(): profile[key] = value.title() return profile user_profile = build_profile('jade', 'marry', location='london', field='computer',sex='female') print(user_profile)

12345678910111213141516

#8-14 汽车:编写一个函数,将一辆汽车的信息存储在一个字典中。这个函数总是接受制造商和型号,还接受任意数量的关键字实参。这样调用这个函数:提供必不可少的信息,以及两个名称—值对,如颜色和选装配件。这个函数必须能够像下面这样进行调用:car = make_car('subaru', 'outback', color='blue', tow_package=True) 打印返回的字典,确认正确地处理了所有的信息。 def make_car(manufacter, types, **infos): specific_infos = {} specific_infos['manufacter'] = manufacter specific_infos['type'] = types for key, value in infos.items(): specific_infos[key] = value return specific_infos car = make_car('subaru', 'outback', color='blue', tow_package=True) print(car) 123456789101112

将函数存储在模块中

函数的优点之一是,使用它们可将代码块与主程序分离。

通过给函数指定描述性名称,可让主程序容易理解的多。更进一步,将函数存储在被称为模块的而独立文件中,再将模块导入到主程序中。import语句允许在当前运行的程序文件夹中使用模块的代码。

通过将函数存储在独立的文件中,可隐藏程序代码的细节,将重点放在程序的高层逻辑上。

这能在众多不同的程序中重用函数将函数存储在独立文件中后,可与其他程序员共享这些文件而不是整个程序、知道如何导入函数还能让你使用其他程序员编写的函数库 导入整个模块

要让函数是可导入的,得先创建模块。

模块 是扩展名为.py的文件,包含要导入到程序中的代码。

pizza.py

def make_pizza(size,*toppings): """ 概述要制作的披萨 """ print("nMaking a "+str(size)+"_inch pizza with the following toppings: ") for topping in toppings: print("- "+topping) 12345

making_pizzas.py

import pizza pizza.make_pizza(16,'pepperoni') pizza.make_pizza(12,'mushrooms','green peppers','extra cheese') 1234

python读取这个文件时,代码行import pizza让python打开文件pizza.py,并将其中的所有函数都复制到这个程序中,但是这个复制是看不到的,隐藏在“幕后”的,这里在making_pizzas.py中可以使用pizza.py中定义的所有函数。

格式:导入模块名称.函数名( ),即module_name.function_name()

导入特定的函数

格式:from module_name import function_name

导入多个函数:from module_name import function_0, function_1, function_2

from pizza import make_pizza make_pizza(16, 'pepperoni') make_pizza(12, 'mushrooms','green peppers','extra cheese') 1234

这种语法,调用函数时无需使用句点“.”

使用as给函数指定别名

如果要导入的函数的名称可能与程序中现有的名称冲突,或者函数的名称太长,可指定简短而独一无二的别名–函数的另一个名称,类似于外号。

使用关键字as将函数重命名为提供的别名,避免与程序中的函数混淆重复

from pizza import make_pizza as mp mp(16, 'pepperoni') mp(12, 'mushrooms', 'green peppers', 'extra cheese') 1234

格式:from module_name import function_name as fn

使用as给模块指定别名

可以给模块指定别名。通过给模块指定简短的别名,使得调用模块中的函数更加轻松

import pizza as p p.make_pizza(16, 'pepperoni') p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') 1234

上述import语句给模块pizza指定了别名p,但该模块中所有函数的名称都没变。

这样不仅能使代码更简洁,还可以让你不再关注模块名,而专注于描述性的函数名。这些函数名明确地指出了函数的功能,对理解代码而言,它们比模块名更重要。

格式:import module_name as mn

导入模块中的所有函数

使用星号(*)运算符可以让python导入模块中的所有函数

from pizza import * make_pizza(16, 'pepperoni') make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') 1234

格式:from module_name import *

import语句中的*让Python将模块pizza中的每个函数都复制到这个程序文件中。由于导入了每个函数,可通过名称来调用每个函数,而无需使用句点表示法。

然而,使用并非自己编写的大型模块时,最好不要采用这种导入方法:如果模块中有函数的名称与你的项目中使用的名称相同,可能导致意想不到的结果:Python可能遇到多个名称相同的函数或变量,进而覆盖函数,而不是分别导入所有的函数。

最佳的做法是,要么只导入你需要使用的函数,要么导入整个模块并使用句点表示法。这能让代码更清晰,更容易阅读和理解。

函数编写指南 应给函数指定描述性名称,且只在其中使用小写字母和下划线 描述性名称可帮助你和别人明白代码想要做什么给模块命名时也应遵循上述约定。 每个函数都应包含简要地阐述其功能的注释,该注释应紧跟在函数定义后面,并采用文档字符串格式 文档良好的函数让其他程序员只需阅读文档字符串中的描述就能够使用它他们完全可以相信代码如描述的那样运行;只要知道函数的名称、需要的实参以及返回值的类型,就能在自己的程序中使用它 给形参指定默认值时,等号两边不要有空格 对于函数调用中的关键字实参,也应遵循这种约定 PEP 8 建议代码行的长度不要超过79字符,这样只要编辑器窗口适中,就能看到整行代码 如果形参很多,导致函数定义的长度超过了79字符,可在函数定义中输入左括号后按回车键,并在下一行按两次Tab键,从而将形参列表和只缩进一层的函数体区分开来大多数编辑器都会自动对齐后续参数列表行,使其缩进程度与你给第一个参数列表行指定的缩进程度相同 如果程序或模块包含多个函数,可使用两个空行将相邻的函数分开,这样将更容易知道前一个函数在什么地方结束,下一个函数从什么地方开始所有的import语句都应放在文件开头,唯一例外的情形是,在文件开头使用了注释来描述整个程序

练习

#8-15 打印模型:将示例 print_models.py 中的函数放在另一个名为 printing_ functions.py 的文件中;在 print_models.py 的开头编写一条 import 语句,并修改这个文件以使用导入的函数。 ''' print_models.py ''' #第一个函数负责处理打印设计的工作,第二个概述打印了哪些设计 def print_models(unprinted_designs, completed_models): """ 模拟打印每个设计,直到没有来打印的设计为止 打印每个设计后,都将其移到列表completed_models中 """ while unprinted_designs: current_design = unprinted_designs.pop() #模拟根据设计制作3D打印模型的过程 print("Printing model: " + current_design) completed_models.append(current_design) def show_completed_models(completed_models): """ 显示打印好的所有模型 """ print("nThe following models have been printed: ") for completed_model in completed_models: print(completed_model) ''' print_functions.py ''' import printing_models as pm unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron'] completed_models = [] pm.print_models(unprinted_designs, completed_models) pm.show_completed_models(completed_models)

1234567891011121314151617181920212223242526272829

#8-16 导入:选择一个你编写的且只包含一个函数的程序,并将这个函数放在另一个文件中。在主程序文件中,使用下述各种方法导入这个函数,再调用它: # import module_name # from module_name import function_name # from module_name import function_name as fn # import module_name as mn # from module_name import * ''' user_profile.py ''' 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 ''' read_profile.py ''' #方法一 import user_profile read_profile = user_profile.build_profile('albert', 'einstein', location='princeton', field='physics') print(read_profile) #方法二 from user_profile import build_profile read_profile = build_profile('albert', 'einstein', location='princeton', field='physics') print(read_profile) #方法三 from user_profile import build_profile as bp read_profile = bp('albert', 'einstein', location='princeton', field='physics') print(read_profile) #方法四 import user_profile as up read_profile = up.build_profile('albert', 'einstein', location='princeton', field='physics') print(read_profile) #方法五 from user_profile import * read_profile = build_profile('albert', 'einstein', location='princeton', field='physics') print(read_profile)

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455

相关知识

小菜鸟的python学习之路(7)
Python学习手册
Python学习第一期
Python小练习
python学习总结day2
python桌面宠物
【毕业设计】基于深度学习的水族馆生物识别 人工智能 深度学习 目标检测 Python
python做桌面宠物
使用Python实现深度学习模型:智能旅游路线规划
Python 入门

网址: 小菜鸟的python学习之路(7) https://www.mcbbbk.com/newsview694687.html

所属分类:萌宠日常
上一篇: 宠物:一线仓鼠,脾气是最暴躁的,
下一篇: 有哪些小型宠物狗

推荐分享