Python入门教程--仓颉

网友投稿 593 2022-05-30

注:文章的附件中有两本学习python经典书籍的pdf文档

Python编程环境设置

一、sublime Text

1.sublime REPL插件安装

(1)安装

先打开插件安装面板:ctrl+shift+P

输入install ,选择Package Control:Install Package

提示安装成功后重新按ctrl+shift+P,选择Package Control:Install Package

之后输入sublimeREPL点击安装

在tools中能够找到sublimeREPL说明安装成功

(2)配置快捷键

首先点击首选项prefrence

其次打开快捷键设置keybindings

输入以下代码后关闭并保存

{"keys":["f5"], "caption":"SublimeREPL:Python - RUN current file", "command":"run_existing_window_command", "args":{ "id":"repl_python_run", "file":"config/Python/Main.sublime-menu"}}

此举是将快捷键设置为F5

2.中文设置

(1)打开安装好的的sublime,选择Preferences下面的Package Contorol选项出现弹窗方框

在弹窗输入install package,选择对应(默认第一个)点击进入

(2)在弹窗出输入chinese,选择插件ChineseLocaloztions(默认第一个)点击安装

(3)等待安装完成,出现中文字体,一般出现就算安装完成了

(4)此时可在Help下面的Language处自由切换成简体中文语言

(5)切换之后的效果,就可以使用中文版了

二、PyCharm相关

1.中文设置

安装 PyCharm 中文插件,打开菜单栏 File,选择 Settings,然后选 Pulgins,点 Marketplace,搜索 chinese,然后点击 install 安装

2.安装注意

3.创建项目时注意

创建项目

这里选择Create New Project,会出现设置项目名称和选择解释器:

选择解释器

注意:这里默认使用的 Python 的虚拟环境,如果你不使用虚拟环境,一定要修改。

如果出现 Interpreter field is empty 表示 Python 的环境变量有问题。当然我们也可以直接选择,请看下面。

Python入门教程--仓颉

选择图中 1,如果 3 位置的下来中选不到 Python.exe, 则点击 2 位置按钮。

选择Python

选择图中1, 如果 3 位置依然没有出现 Python.exe,则点击 2 位置按钮选择 Python 的安装目录,找到你安装的 Python 目录,然后选择 Python.exe。

然后点击Create即可。

那么现在项目就创建成功了

项目界面

在上图中,去掉Show tips on startup,不用每次都打开欢迎界面,然后关闭即可。

4.创建 Python 文件

在项目名称的位置点击鼠标右键,选择New > Python File

新建Python文件

输入文件名称,点击 OK 即可。

在文件中输入代码:

然后在文件中任意空白位置点击鼠标右键,选择运行:

运行Python

在界面的下方,显示 Python 代码的运行结果

第2节.变量和简单数据类型

2.1变量的命名和使用:

变量名只能包含字母、数字和下划线。不能包含空格。

不要将python关键字和函数名作为变量名

应使用小写的python变量名

同时给多个变量赋值

x,y,z=1,2,3

2.2字符串的处理(用引号括起的都是字符串)

方法的应用

name= "ada lovelace" print(name) print(name.title()) #首字母大写,常用于打印名字 print(name.upper()) #全部大写 print(name.lower()) #全部小写

字符串的拼接

first_name="ada" last_name="lovelace" full_name=f"{first_name}{last_name}" #将first_name与last_name拼接 print(f"Hello,{full_name.title()}!") #将hello与经过方法title处理的名字拼接

2.3转义字符

制表符

print("python") print("\tpython")

换行符

print("c++") print("\nc++")

2.4删除空白

best_language=" python " print(best_language) print(best_language.lstrip()) #lstrip()方法删除字符串开头的空白 print(best_language.rstrip()) #rstrip()方法删除字符串末尾的空白 print(best_language.strip()) #strip()方法删除字符串两头的空白

2.5数

将任意两个数相除时,得到的结果总是浮点数

书写很大的数时,可以使用下划线将其中的数字分组,运行时下划线不会被打印

number=14_000_000_000_000 print(number)

数据类型转换

Str 将其他类型转换成字符串

Bool 将其他类型转换成布尔型

Int 将其他类型转换成整型(若是浮点型则会保留整数部分)

Float 将其他类型转换成浮点型

money=1000 print((float(money))) #将字符串类型的1000转换为浮点型的1000.0

2.6将数据输出到文件中

fp=open('E:' , 'a+') #a+为输出格式 print('I love you.' , file=fp) fp.close()

第3节列表以及遍历

3.1列表的特性:有序,元素可以重复,可以存放多种类型

注:索引是从0开始(开头起始)

也可以从-1开始(结尾起始)

3.2修改、添加和删除元素

修改

motorcycles=['honda','yamaha','suzuki'] print(motorcycles) motorcycles[0]='ducati' #将motorcycles中索引为0的honda修改为ducati print(motorcycles)

附加

motorcycles=['honda','yamaha','suzuki'] print(motorcycles) motorcycles.append('ducati') #在列表末尾添加元素ducati print(motorcycles)

也可用创建一个空列表,再一个个添加元素

插入

motorcycles=['honda','yamaha','suzuki'] print(motorcycles) motorcycles.insert(0,'ducati') #在索引为0的元素前面添加元素ducati print(motorcycles)

删除

根据索引删除元素但不可使用它

motorcycles=['honda','yamaha','suzuki'] print(motorcycles) del motorcycles[1] #删除索引为1的元素 print(motorcycles)

删除列表末尾的元素并使用它(弹出元素)

popped_motorcycle=motorcycles.pop() #定义被方法pop()删除的元素 print(motorcycles) #打印原列表 print(popped_motorcycle) #打印被删除的元素

根据值删除元素并使用它的值(弹出元素)

motorcycles=['honda','yamaha','suzuki','ducati'] too_exepensive='ducati' #定义要删除的元素 motorcycles.remove(too_exepensive) #删除被定义的元素 print(motorcycles) #打印原列表 print(f"\nA{too_exepensive.title()} is too expensive for me") #将被删除的元素插入句子中并换行打印这个句子

3.3组织列表(在并非所有值都是小写时,按字母排序要复杂一点)

使用sort()方法对列表永久排序(按字母顺序排序)

cars=['bmw','audi','toyota','subaru'] cars.sort() print(cars)

按与字母顺序相反的顺序排列元素(向sort()方法传递函数reverse=True)

cars=['bmw','audi','toyota','subaru'] cars.sort(reverse=True) print(cars)

使用函数sorted()对列表临时排序(字母顺序)

print("\nHere is the sorted list:") print(cars) print("\nHere is the original list again:") print(cars)

倒着打印列表

cars=['bmw','audi','toyota','subaru'] print(cars) cars.reverse() print(cars)

确定列表的长度

cars=['bmw','audi','toyota','subaru'] len(cars) #列表长度用列表元素的个数表示 print(len(cars))

3.4遍历整个列表

magicians=['alice','david','carolina'] for magician in magicians: #(1) #for循环语句重复执行(1)和(2)的代码行 print(magician) #(2)

3.5创建数值列表

使用函数range()

for value in range(1,6): #会循环打印出1,2,3,4,5 print(value) for value in range(7): #只指定一个参数时,会从0开始打印 print(value) numbers=list(range(1,5)) #使用函数list()将range()的结果直接转化为列表 print(numbers) even_numbers=list(range(2,11,2)) #第2个2是指定的步长,此时range函数会从2开始然后不断加2直到等于或超过终值 print(even_numbers)

函数range()可以创建几乎任何需要的数集

squares=[] for value in range(1,11): square=value **2 #对value的每一个值进行乘方运算 squares.append(square) #将每一个运算后的值加入到空白列表中去 print(squares)

对数字进行简单的统计计算

digits=[1,2,3,4,5,6,7,8,9,0] min(digits) #求出列表中的最小值 print((min(digits))) max(digits) #求出列表中的最大值 print((max(digits))) sum((digits)) #求和 print(sum(digits))

列表解析

列表解析将for循环和创建新元素的代码合并成一行,并自动附加新元素

squares=[value2 **2 for value2 in range(1,11)] print(squares)

3.6多维容器(多种形式的容器和数据类型可以共存于一个列表)

list_a=[32,423,523,324,123,54,67,'Jack'] list_b=['Job', 'Bob', 'Steven',123,8656] #二维列表 list_x=[[1,7,4,9,4],list_a,list_b,'Kin',54,(7,43,2,98),8] #多维列表 print(list_x) print(list_x[1]) #打印列表list_X中索引为1元素 print((list_x[0][3])) #打印列表list_x中索引为0的元素中的索引为3的子元素

3.7使用列表的一部分

切片

要创建切片,可指定要使用的第一个元素和最后一个元素的索引

players=['charles','martina','michael','florence','eli'] print(players[0:4])

也可以通过负数索引来打印末尾的任意切片

players=['charles','martina','michael','florence','eli'] print(players[-3:])

如果没有指定第一个索引,python将自动从列表开头开始

也可以在方括号内指定第三个值,这个值用来告诉python在指定范围内每隔多少个元素提取一个

遍历切片

遍历列表的部分元素,可以在for循环中使用切片

players=['charles','martina','michael','florence','eli'] print("Here are the first three players on my team:") for player in players[:3]: print(player.title())

复制列表

要想复制列表,可创建一个包含整个列表的切片

players=['charles','martina','michael','florence','eli'] players2=players[:] print(players2)

3.8元组(相当于不可更改的列表,使用圆括号来标识)

定义元组

dimensions=(200,50) print(dimensions[0]) print(dimensions[1])

严格意义上来讲,元组是由逗号标识的,哪怕定义一个只有一个元素的元组,也要在这个元素末尾加上逗号

例如my_t=(3,)

遍历元组中的所有值

dimensions=(200,50) for dimension in dimensions: print(dimension)

给储存元组的变量赋值

dimensions=(200,50) print("Original dimensions:") for dimension in dimensions: print(dimension) dimensions=(400,100) print("\nModified dimensions:") for dimension in dimensions: print(dimension)

第4节.if语句

4.1 if语句的简单示例

cars=['audi','bmw','subaru','toyota'] for car in cars: if car=='bmw': print(car.upper()) else: print(car.title())

4.2 if语句

if-else语句

age=17 if age>=18: print("You are old enough to vote!") print("Have you registered to vote yet?") else: print("Sorry,you are too young to vote.") print("Please register to vote as soon as you turn 18!")

if-elif-else结构

用于检查超过两个的情形

''' 我们以一个根据年龄收费的游乐场为例: 4岁以下免费 4~18岁收费25美元 18(含)岁以上收费40美元 ''' age=12 if age <4: print("Your admission cost is $0") elif age < 18: #只会执行通过测试的代码 print("Your admission cost is $25") else: print("Your admission cost is $40") #现在我们将上面的代码进行简化 age =12 if age <4: price=0 elif age <18: price=25 else: price=40 print(f"Your admission cost is ${price}.") #else代码块可以省略,只要不满足if或elif的测试条件,else中的代码就会执行 #如果知道最终要测试的条件,就可以考虑用一个elif代码块代替else代码块 #if-elif-else结构功能强大,但仅适合用于只有一个条件满足的情况,遇到了通过测试的情况,剩下的代码就会跳过执行

测试多个条件

requested_toppings=['mushrooms','extra cheese'] if 'mushrooms' in requested_toppings: print('Adding mushrooms.') if 'pepperoni' in requested_toppings: print('Adding pepperoni.') if 'extra cheese' in requested_toppings: print('Adding extra cheese.') print("\nFinished making your pizza!") #首先创建一个列表,然后依次检查某一元素是否在列表中最后输出结果 #如果只想执行一个代码块,就是用if-elif-else结构;如果要执行多个代码块,使用一系列独立的if语句

4.3使用if语句检查列表

检查特殊元素

requested_toppings=['nushrooms','green peppers','extra cheese'] for requested_topping in requested_toppings: if requested_topping == 'green peppers': print("Soory we are out of green peppers!") else: print(f"Adding {requested_topping}") print(f"\nFinished making your pizza!")

确定列表不是空的

运行for循环前确定列表是否为空很重要

requested_toppings=[] if requested_toppings: for requested_topping in requested_toppings: print(f"Adding {requested_topping}") print ("\nFinished making your piaaz!") else: print("Are you sure want a plain pizza?")

使用多个列表:

available_toppings = ['mushrooms','olives','green peppers','pepperoni','pineapple','extra cheese'] requested_toppings = ['mushrooms','french fris','extra cheese'] for requested_topping in requested_toppings: if requested_topping in available_toppings: print(f"Adding {requested_topping}") else: print(f"Sorry,we don't have {requested_topping}") print("\nFinished making your pizza!")

第5节.字典

5.1一个简单的字典

字典的特性:无序,键对值,键不可重复

alien_0={'color':'green','points':'5'} print(alien_0['color']) #每一个值对应一个键,用于快速查找 print(alien_0['points']) #字典中可以包含任意键对值

5.2使用字典

添加键对值

alien_0={'color':'green','points':'5'} print(alien_0) alien_0['x_position'] = 0 alien_0['y_position'] = 0 print(alien_0)

在空字典中添加键对值

alien_0={} alien_0['color'] = 'green' alien_0['points'] = 5 print(alien_0)

修改字典中的值

aalien_0={'color':'green'} print(f"The alien is {alien_0['color']}.") ##!!!注意此处的点和括号!!! alien_0['color']=['yellow'] print(f"The alien is now {alien_0}.")

删除键对值

alien_0={'color':'green','points':'5'} print(alien_0) del alien_0['points'] print(alien_0)

长字典的构成

favorite_languages={ 'jen':'python', 'sarah':'c', 'edward':'ruby', 'phil':'python' }

使用get()来访问值

alien_0={'color':'green','speed':'slow'} point_value=alien_0.get('points','No point value assigned.') print(point_value) #方法get()的第一个参数用于指定键,第二个参数为指定的键不存在时要返回的值,若没有指定则返回none #如果指定的键有可能不存在,应考虑使用方法get()

5.3遍历字典

遍历所有键对值

user_0={ 'username':'efermi', 'first':'enrico', 'last':'fermi' } for key,value in user_0.items(): #items()方法:以列表返回可遍历的(键,值)元组数组 print(f"\nkey:{key}") print(f"value:{value}")

5.4集合

特点:无序,元素不重复,本质上是只有键的字典

集合的运算

set1={123,43,525,63,643,436} set2={45,55,66,87,123,63,58} print(set1&set2) #获取交集 print(set1|set2) #获取并集 print(set1-set2) #获取差集

条件测试

检查是否相等(检查时区分大小写)

car = 'Audi' car=='audi' car = 'Audi' car.lower()=='audi'

检查是否不相等

requested_topping='mushrooms' irequested_topping!='anchovies'

数值比较

age=18 age==18: age=18 age<21: age >=5: age=18 age<=21: age >=5:

##使用and或or检查多个条件

#使用and时,如果至少一个测试没有通过,整个表达式为Flas #使用or时,至少有一个条件满足就能通过整个测试 age_0=21 age_1=18 age_0>=21 and age_1>=21 age_0=21 age_1=18 age_0>=21 or age_1>=21

检查特值是否包含在列表中

requested_toppings=['mushrooms','onions','pineapple'] 'mushrooms' in requested_toppings 'banana' in requested_toppings banned_users=['andrew','carolina','david'] 'marie' not in banned_users

布尔表达式

game_active=True can_edit=Flase

条件测试

检查是否相等(检查时区分大小写)

car = 'Audi' car=='audi' car = 'Audi' car.lower()=='audi'

检查是否不相等

requested_topping='mushrooms' irequested_topping!='anchovies'

数值比较

age=18 age==18: age=18 age<21: age >=5: age=18 age<=21: age >=5:

##使用and或or检查多个条件

#使用and时,如果至少一个测试没有通过,整个表达式为Flas #使用or时,至少有一个条件满足就能通过整个测试 age_0=21 age_1=18 age_0>=21 and age_1>=21 age_0=21 age_1=18 age_0>=21 or age_1>=21

检查特值是否包含在列表中

requested_toppings=['mushrooms','onions','pineapple'] 'mushrooms' in requested_toppings 'banana' in requested_toppings banned_users=['andrew','carolina','david'] 'marie' not in banned_users

布尔表达式

game_active=True can_edit=Flase

第6节.用户输入和while循环

6.1函数input()

简单的输入

massage=input("Tell me something,and I will repeat it back to you:") print(massage)

输入数值

age=input("How old are you?") print(age) #此时用户输入会被默认解释为字符串 age=input("How old are you?") age=int(age) #此时就将用户输入指定成了数值 print(age) #更加简便的指定用户输入 age=int(input("How old are you?")) print(int(age))

6.2求模运算符

A=4%3 print(A) #将两个数相除并返回余数

6.3while循环

while循环简介

current_number=1 while current_number<=5: #循环从1数到5 print(current_number) current_number +=1

让用户选择何时退出

prompt="\nTell me something, and I will repeat it back to you:" prompt+="\nEnter 'quit' to end the program. " message="" #使用空字符定义变量,用于接收输入的字符串 while message != 'quit': message=input(prompt) print(message)

上述代码的缺点是将quit也打印了出来,下面用一个if语句优化它

prompt="\nTell me something, and I will repeat it back to you:" prompt+="\nEnter 'quit' to end the program. " message="" while message != 'quit': message=input(prompt) if message !='quit': print(message)

使用标志

prompt="\nTell me something, and I will repeat it back to you:" prompt+="\nEnter 'quit' to end the program. " active=True while active: message=input(prompt) if message=='quit': active=False else: print(message)

使用break函数退出循环

prompt="\nTell me something, and I will repeat it back to you:" prompt+="\nEnter 'quit' to end the program. " while True: city=input(prompt) if city == 'quit': break #break语句也可以用于退出遍历列表或字典的for循环 else: print(f"I'd love to go to {city.title()}")

在循环中使用continue

current_number=0 while current_number <10: current_number += 1 if current_number%2==0: continue print(current_number)

当程序陷入无限循环时,按CTRL+C可以关闭程序

6.4使用while循环处理列表和字典

在列表之间移动元素

#首先,创建一个待验证用户列表 #和一个用于存储已验证用户的空列表 unconfirmed_users = ['alice', 'brian', 'candace'] confirmed_users = [] #验证每个用户,直到没有未验证用户为止 #将每个经过验证的列表都移到已验证用户列表中 while unconfirmed_users: current_user = unconfirmed_users.pop() print("Verifying user: " + current_user.title()) confirmed_users.append(current_user) #将元素添加到已验证列表中 #显示所有已验证的用户 print("\nThe following users have been confirmed:") for confirmed_user in confirmed_users: print(confirmed_user.title())

删除为特定值的所有列表元素

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] print(pets) while 'cat' in pets: pets.remove('cat') print(pets)

使用用户输入来填充字典

responses = {} #设置一个标志,指出调查是否继续 polling_active = True while polling_active: #提示输入被调查者的名字和回答 name = input("\nWhat is your name? ") response = input("Which mountain would you like to climb someday? ") #将答卷存储在字典中 responses[name] = response #看看是否还有人要参与调查 repeat = input("Would you like to let another person respond? (yes/ no) ") if repeat == 'no': polling_active = False #调查结束,显示结果 print("\n--- Poll Results ---") for name, response in responses.items(): print(name + " would like to climb " + response + ".")

第7节.函数

7.1定义函数

定义一个打印问候语的函数

def greet_user(): '''显示简单的问候语''' print("Hello") #def关键字告诉python,我要定义一个函数

向函数传递信息

def greet_user(username): '''显示简单的问候语''' print(f"Hello,{username.title()}!") greet_user('jesse') #函数被调用时被传达参数jesse #上面函数中的username就是一个形参 #jesse就是一个实参

7.2传递实参

实参的顺序与形参的顺序要相同

位置实参

def describe_pet(animal_type,pet_name): '''显示宠物信息''' print(f"\nI have a {animal_type}.") print(f"My {animal_type}'s name is {pet_name.title()}") describe_pet('hamster','harry') #当你想再描述一个宠物时,只需要再调用一次函数即可

关键字实参

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

def describe_pet(animal_type,pet_name): '''显示宠物信息''' print(f"\nI have a {animal_type}.") print(f"My {animal_type}'s name is {pet_name.title()}") describe_pet(animal_type='hamster',pet_name='harry') #在调用函数时,明确指出各实参所对应的形参

默认值

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

def describe_pet(animal_type,pet_name='harry'): '''显示宠物信息''' print(f"\nI have a {animal_type}.") print(f"My {animal_type}'s name is {pet_name.title()}") describe_pet('hamster') #定义函数时指定了一个形参的默认值,所以调用函数时只需要指定另一个形参所对应的实参

7.3返回值

def get_formatted_name(first_name,last_name): '''返回整洁的姓名''' full_name=f"{first_name} {last_name}" return full_name.title() musician=get_formatted_name('jimi','hendrix') print(musician) #此方法可以用于存储和调用大量的姓名

使实参变成可选的

def get_formatted_name(first_name,mid_name,last_name): '''返回整洁的姓名''' full_name=f"{first_name} {mid_name} {last_name}" return full_name.title() musician=get_formatted_name('john','lee','hooker') print(musician) #上面的代码在指定2个实参时无法运行 def get_formatted_name(first_name,mid_name,last_name=''): '''返回整洁的姓名''' full_name=f"{first_name} {mid_name} {last_name}" return full_name.title() musician2=get_formatted_name('john','lee') #当函数的实参是三个值而你只指定了2个时函数不会执行,此时可以将函数的一个实参指定为空值 print(musician2) #上面的代码在指定2个实参时可以运行 #可以将上面的两种情况合并如下,使其变成可选的 def get_formatted_name(first_name,last_name,middle_name=''): '''返回整洁的姓名''' if middle_name: full_name=f"{first_name} {middle_name} {last_name}" else: full_name=f"{first_name} {last_name}" return full_name.title() musician=get_formatted_name('john','hooker') print(musician) musician=get_formatted_name('john','lee','hooker') print(musician)

返回字典

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

def build_person(first_name,last_name): '''返回一个字典,其中包含有关一个人的信息''' person={'first':first_name,'last':last_name} return person musician=build_person('jimi','hendrix') print(musician) #下面扩展这个函数: def build_person(first_name,last_name,age=None): '''返回一个字典,其中包含有关一个人的信息''' person={'first':first_name,'last':last_name} if age: person['age']=age return person musician=build_person('jimi','hendrix',age=27) print(musician)

结合用函数和while循环

def get_formatted_name(first_name,last_name): '''返回整洁的姓名''' full_name=f"{first_name} {last_name}" return full_name.title 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(f"\nHello,{formatted_name}!") #while循环让用户输入姓名,依次输入名和性

传递列表

将列表传递给函数后,函数就能直接访问其内容

def greet_users(names): '''向列表中的每位用户发出简单的问候''' for name in names: msg=f"Hello,{name.title()}" print(msg) usernames=['hannah','ty','margot'] greet_users(usernames)

在函数中修改列表

#首先创建一个列表,其中包含一些要打印的设计。 unprinted_designs=['phone case','robot pendant','dodecahedron'] completed_models=[] #模拟打印每个设计,直到没有未打印的设计为止。 #打印每个设计后,都将其移到列表completed_models中 while unprinted_designs: current_design=unprinted_designs.pop() print(f"Printing model:{current_design}") completed_models.append(current_design) #显示打印好的所有模型 print("\nThe following models have been printed:") for completed_model in completed_models: print(completed_models) '''为了重新组织上述代码,我们可以编写两个函数''' def print_models(unprinted_designs,completed_models): """ 模拟打印每个设计,直到没有未打印的设计为止 打印每个设计后,都将其移到列表completed_models中 """ while unprinted_designs: current_design=unprinted_designs.pop() print(f"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=['phone case','robot pendant','dodecahedron'] completed_models=[] print_models(unprinted_designs,completed_models) show_completed_models(completed_models)

禁止函数修改列表(向函数传递列表的副本而非原件)

print_models(unprinted_designs[:],completed_models)

7.4传递任意数量的实参

def make_pizza(*toppings): """打印顾客点的所有配料""" print(toppings) make_pizza('pepperoni') make_pizza('mushrooms','green peppers','extra cheese') #形参名中的*让python创建一个名为toppings的空元组,并将收集到的所有值都封装到这个元组中

结合使用位置实参和任意数量实参

def make_pizza(size,*toppings): """概述要制作的比萨""" print(f"\nMaking a {size}-inch pizza with the following toppings:") for topping in toppings: print(f"-{topping}") make_pizza(6,'pepperoni') make_pizza(12,'mushrooms','green peppers','extra cheese') #通用形参名*args也收集任意数量的位置实参

使用任意数量的关键字实参

def build_profile(first,last,**user_info): """创建一个字典,其中包含我们知道的有关用户的一切""" user_info['first_name']=first user_info['last_name']=last return user_info user_profile=build_profile('albert','einstein', location='princeton', field='pyhsics') print(user_profile) #通用形参名**kwargs用于收集任意数量的关键字实参

7.5将函数存储在模块中

导入整个模块

import文件要放在文件开头

#下面这个模块为pizza.py def make_pizza(size,*toppings): """概述要制作的比萨""" print(f"\nMaking a {size}-inch pizza with the following toppings:") for topping in toppings: print(f"-{topping}") #在pizza.py所在的目录中创建一个名为making_pizzas.py的文件,并导入刚刚创建的模块 import pizza #此行代码会将pizza.py文件中的所有函数都复制到程序中 pizza.make_pizza(16,'pepperoni') pizza.make_pizza(12,'mushrooms','green peppers','extra cheese')

导入模块中的特定函数

from pizza import make_pizza,make_pizza2,make_pizza3 #使用逗号分隔开各个函数,就可以导入任意数量的函数 pizza.make_pizza(16,'pepperoni') pizza.make_pizza(12,'mushrooms','green peppers','extra cheese')

使用as给函数指定别名

此方法可以给函数指定别名

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

使用as给模块指定别名

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

导入模块中的所有函数

#使用星号*运算符可以让python导入模块中的所有函数 from pizza import* make_pizza(16,'pepperoni') make_pizza(12,'mushrooms','green peppers','extra cheese')

第8节.类

8.1创建和使用类

使用类几乎可以模拟任何东西

创建一个类

from _typeshed import Self class Dog: """一次模拟小狗的简单尝试""" def __init__(self,name,age): """初始化属性name和age""" self.name=name #self.name=name获取与形参name相关联的值 self.age=age ### 以self为前缀的变量可以供类中所有方法使用 def sit(self): """模拟小狗收到命令时蹲下""" print(f"{self.name} is now sitting.") def roll_over(self): """模拟小狗收到命令时打滚""" print(f"{self.name} rolled over!")

根据类创建实例

class Dog: """一次模拟小狗的简单尝试""" def __init__(self,name,age): #形参self自动向类中的方法传递指定的属性 """初始化属性name和age""" self.name=name self.age=age def sit(self): """模拟小狗收到命令时蹲下""" print(f"{self.name} is now sitting.") def roll_over(self): """模拟小狗收到命令时打滚""" print(f"{self.name} rolled over!") my_dog=Dog('Willie',6) #指定实例的属性 print(f"My dog's name is {my_dog.name}.") #my_dog.name代码用来访问实例的属性 print(f"My dog's name is {my_dog.age} years old.") my_dog=Dog('Willie',6) my_dog.sit() #调用实例的方法 my_dog.roll_over()

8.2使用类和实例

car类

class Car: """一次模拟汽车的简单尝试""" def __init__(self,make,model,year): """初始化描述汽车的属性。""" self.make=make self.model=model self.year=year def get_descriptive_name(self): """返回整洁的描述性信息""" long_name=f"{self.year} {self.make} {self.model}" return long_name.title() my_new_car=Car('audi','a4',2019) print(my_new_car.get_descriptive_name())

给属性指定默认值

classclass Car: """一次模拟汽车的简单尝试""" def __init__(self,make,model,year): """初始化描述汽车的属性。""" self.make=make self.model=model self.year=year self.odometer_reading=0 #创建一个名为odometer_reading的属性,并将其初始值设为0,该值不会被传递给类的参数改变 def get_descriptive_name(self): """返回整洁的描述性信息""" long_name=f"{self.year} {self.make} {self.model}" return long_name.title() def read_odometer(self): """打印一条指出汽车里程的消息""" print(f"This car has {self.odometer_reading} miles on it.") my_new_car=Car('audi','a4',2019) print(my_new_car.get_descriptive_name) my_new_car.read_odometer()

直接修改属性的值

my_new_car.odometer_reading=23 my_new_car.read_odometer() ##通过方法修改属性的值 class Car: """一次模拟汽车的简单尝试""" def __init__(self,make,model,year): """初始化描述汽车的属性。""" self.make=make self.model=model self.year=year def get_descriptive_name(self): """返回整洁的描述性信息""" long_name=f"{self.year} {self.make} {self.model}" return long_name.title() def read_odometer(self): """打印一条指出汽车里程的消息""" print(f"This car has {self.odometer_reading} miles on it.") def update_odometer(self,mileage): """将里程碑读数设置为指定的值""" Self.odometer_reading=mileage my_new_car=Car('audi','a4',2019) print(my_new_car.get_descriptive_name()) my_new_car.update_odometer(23) #在括号内传递参数 my_new_car.read_odometer()

8.3继承

子类的方法__init__

一个类继承 另一个类时,它将自动获得另一个类的所有属性和方法

class Car(): """一次模拟汽车的简单尝试""" def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.odometer_reading = 0

继承时,父类必须包含在当前文件中,且位于子类前面

def get_descriptive_name(self): long_name = f"{self.year} {self.make} {self.model}" return long_name.title() def read_odometer(self): print(f"This car has {self.odometer_reading} miles on it.") def update_odometer(self,mileage): if mileage >= self.odometer_reading: self.odometer_reading=mileage else: print("You can't roll back an odometer!") def increment_odometer(self,miles): self.odometer_reading +=miles class ElectricCar(Car): """电动汽车的独特之处""" def __init__(self, make, model, year): """初始化父类的属性""" super().__init__(make, model, year) my_tesla=ElectricCar('tesla','model s',2016) print(my_tesla.get_descriptive_name())

super() 是一个特殊函数,帮助Python将父类和子类关联起来。

在Python 2.7中,继承语法稍有不同,函数super() 需要两个实参:子类名和对象self

给子类定义属性和方法

class Car: """一次模拟汽车的简单尝试""" def __init__(self,make,model,year): """初始化描述汽车的属性。""" self.make=make self.model=model self.year=year def get_descriptive_name(self): """返回整洁的描述性信息""" long_name=f"{self.year} {self.make} {self.model}" return long_name.title() def read_odometer(self): """打印一条指出汽车里程的消息""" print(f"This car has {self.odometer_reading} miles on it.") def update_odometer(self,mileage): """将里程碑读数设置为指定的值""" Self.odometer_reading=mileage class ElectricCar(Car): """电动汽车的独特之处""" def __init__(self, make, model, year): """ 初始化父类的各项属性 再初始化电动汽车特有的属性 """ super().__init__(make, model, year) self.battery_size=75 def describe_battery(self): """打印一条描述电瓶容量的消息""" print(f"This car has a {self.battery_size} -kwh battery.") my_tesla=ElectricCar('tesla','model s',2019) print(my_tesla.get_descriptive_name()) #调用父类的方法 my_tesla.describe_battery()

重写父类的方法:

在子类中定义一个和父类中的某一方法同名的方法即可重写父类中相应的方法

将实例用作属性

class Battery: """一次模拟电动汽车电瓶的尝试""" def __init__(self,battery_size=75): """初始化电瓶的属性""" self.battery_size=battery_size def describe_battery(self): """打印一条描述电瓶容量的消息""" print(f"This car has a {self.battery_size} -kwh battery.")

导入类

使用from car import Car 可以从一个模块中导入多个类,使用逗号隔开

最后给大家一个语法速查地图(来自蟒蛇书)

点击查看

附件: 编辑器安装说明.pdf 389.53KB 下载次数:2次

附件: Python背记手册.pdf 0B 下载次数:3次

附件: 蟒蛇PPTpython学习1-11章.zip 7.47MB 下载次数:3次

附件: Python编程:从入门到实践.pdf 4.98MB 下载次数:2次

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:[Python从零到壹] 四.网络爬虫之入门基础及正则表达式抓取博客案例 | 【生长吧!Python】(python从0到1)
下一篇:云数据中心网络与SDN: 技术架构与实现(云数据中心网络与sdn)
相关文章