0222
- 不需要分号,不需要规定类型,直接赋值,且中途可以随时修改变量的值
message="Hello Python world!"
print(message)
message="Hello Python Crash Course world!"
print(message)
Hello Python world!
Hello Python Crash Course world!
- 只要有引号包含就是字符串,单双引号都可以
message1="This new language’s name is 'Python'!"
message2='I told your friend,"My thought is not enough."'
- 修改字符串的大小写
- title()
message="My name is Zichel, I'm learning Python!"
print(message.title())
My Name Is Zichel, I’M Learning Python!
可以用于识别如名字、地名等需要首字母大写的词语
- upper()
message="My name is Zichel, I'm learning Python!"
print(message.upper())
MY NAME IS ZICHEL, I’M LEARNING PYTHON!
- lower()
message="My name is Zichel, I'm learning Python!"
print(message.lower())
my name is zichel, i’m learning python!
在存储数据时比较有用,无法依靠用户提供正确大小写,就统一先小写
- 在字符串中使用变量f函数(3.5以前叫做format)
first_name="ada"
last_name="lovelace"
#注意其中的空格也会被回显出来
full_name=f"{first_name} {last_name}"
print("Hello,{full_name}")
Hello,{full_name}
first_name="ada"
last_name="lovelace"
#注意其中的空格也会被回显出来
full_name=f"{first_name} {last_name}"
print(f"Hello,{full_name.title()}")
Hello,Ada Lovelace
first_name="ada"
last_name="lovelace"
#注意其中的空格也会被回显出来
full_name=f"{first_name} {last_name}"
message=f"Hello,{full_name.title()}"
print(message)
Hello,Ada Lovelace
- 制表符和换行符
print("Python")
# \t制表符,就是前面空几个
print("\tPython")
# \n换行符
print("Language:\nPython\nC\nJavaScript")
# 同时换行制表
print("Language:\n\tPython\n\tC\n\tJavaScript")
Python
Python
Language:
Python
C
JavaScript
Language:
Python
C
JavaScript
- 同时给多个变量赋值
x,y,z=0,0,0
- 常量全大写
MAX_CONNECTION=5000
- 列表查询增改
- 在末尾添加元素append(),帮助动态创建列表
- 任意处插入insert()
- 不知道列表长度时最后一个元素的索引可以使用-1
letters=['a','b','c','d']
print(letters)
print(letters[0],letters[1],letters[2],letters[-1])
print(letters[0],letters[1],letters[2],letters[3])
letters[0]='z'
print(letters[0])
letters.append('e')
print(letters)
letters.insert(1,'g')
print(letters)
[‘a’, ‘b’, ‘c’, ‘d’]
a b c d
a b c d
z
[‘z’, ‘b’, ‘c’, ‘d’, ‘e’]
[‘z’, ‘g’, ‘b’, ‘c’, ‘d’, ‘e’]
- 列表删除
- del语句(已知元素在列表中的位置
- pop(),将元素从列表中删除,并接着使用这个值(已知的任意位置
- remove()根据值删除,也可以接着使用
letters=['a','b','c','d','e','f']
print(letters)
del letters[0]
print(letters)
popped_letter=letters.pop()
print(letters)
print(popped_letter)
second_letter=letters.pop(1)
print(letters)
print(second_letter)
dont_like='d'
letters.remove(dont_like)
print(letters)
print(f"\n The letter that i don't like is {dont_like}")
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
[‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
[‘b’, ‘c’, ‘d’, ‘e’]
f
[‘b’, ‘d’, ‘e’]
c
[‘b’, ‘e’]The letter that i don’t like is d
- 组织列表
- sort()属于永久排序
names=['Adam','Cindy','David','Bob']
names.sort()
print(names)
names.sort(reverse=True)
print(names)
[‘Adam’, ‘Bob’, ‘Cindy’, ‘David’]
[‘David’, ‘Cindy’, ‘Bob’, ‘Adam’]
- sorted()临时排序
names=['Adam','Cindy','David','Bob']
print("Here is the original list")
print(names)
print("Here is the sorted list")
print(sorted(names))
print("Here is the original list")
print(names)
Here is the original list
[‘Adam’, ‘Cindy’, ‘David’, ‘Bob’]
Here is the sorted list
[‘Adam’, ‘Bob’, ‘Cindy’, ‘David’]
Here is the original list
[‘Adam’, ‘Cindy’, ‘David’, ‘Bob’]
- 逆序打印
names=['1Adam','2Cindy','3David','4Bob']
print(names)
names.reverse()
print(names)
[‘1Adam’, ‘2Cindy’, ‘3David’, ‘4Bob’]
[‘4Bob’, ‘3David’, ‘2Cindy’, ‘1Adam’]
reverse虽然永久改变,但是要变回来再reverse一边就好了
- 求长度
lens(列表名)
0223
- 遍历整个列表
列表一般定义是复数形式,使用for循环的时候直接从单词中截取单数作为变量,即其中的每一项
magicians=['alice','david','carolina']
for magician in magicians:print(f"{magician.title()},that was a great trick!")
Alice,that was a great trick!
David,that was a great trick!
Carolina,that was a great trick!
不用打括号,直接缩进即可
magicians=['alice','david','carolina']
for magician in magicians:print(f"{magician.title()},that was a great trick!")print(f"I can't wait to see {magician.title()} next time.\n")
print("Thank you all")
冒号和缩进注意一下
- range()生成一系列数
#只生成1-1,从第一个数开始,第二个数的前一个停止
for value in range(1,5):print(value)#也可以只指定一个参数,将从0到这个参数的前一个数
for value in range(6):print(value)
1
2
3
4
0
1
2
3
4
5
- 创建数字列表使用list()直接转换range即可
numbers=list(range(1,6))
print(numbers)
#还可以指定步长
#从2开始不断+2,直到达到或者超过11
even_numbers=list(range(2,11,2))
print(even_numbers)
[1, 2, 3, 4, 5]
[2, 4, 6, 8, 10]
- 使用range可以创建几乎任意数字集
squares=[]
#使用临时变量版本
for value in range(1,11):square=value**2squares.append(square)
print(squares)#不使用临时变量版本
for value in range(1,11):squares.append(value**2)
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> digits=[1,2,3,4,5,6,7,8,9,0]
>>> min(digits)
0
>>> max(digits)
9
>>> sum(digits)
45
- 列表解析(简化步骤)
- 先指定描述性列表名
- 然后指定方括号定义表达式,用于生成要存储到列表中的值
- 编写for循环,用于给表达式提供值
- 此处的for循环没有冒号
squares=[value**2 for value in range(1,11)]
print(squares)
- 列表生成任意子集
players=['adam','bob','cindy','dory','emily']
print(players[0:2])
#省略第一个,自动从泪飙开头开始
print(players[:2])
print(players[1:3])
#省略第二个,自动停到结尾
print(players[2:])
print(players[-3:])
[‘adam’, ‘bob’]
[‘adam’, ‘bob’]
[‘bob’, ‘cindy’]
[‘cindy’, ‘dory’, ‘emily’]
[‘cindy’, ‘dory’, ‘emily’]
- 遍历切片
players=['adam','bob','cindy','dory','emily']
print("Here are the first three players in our team:")
for player in players[:3]:print(player)
Here are the first three players in our team:
adam
bob
cindy
- 复制列表
my_foods=['pizza','falafel','carrot cake']
#全复制
friend_foods=my_foods[:]
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
my_foods.append('cannoli')
friend_foods.append('spagetti')
print("Now my favorite foods are:")
print(my_foods)
print("\nNow my friend's favorite foods are:")
print(friend_foods)
My favorite foods are:
[‘pizza’, ‘falafel’, ‘carrot cake’]My friend’s favorite foods are:
[‘pizza’, ‘falafel’, ‘carrot cake’]
Now my favorite foods are:
[‘pizza’, ‘falafel’, ‘carrot cake’, ‘cannoli’]Now my friend’s favorite foods are:
[‘pizza’, ‘falafel’, ‘carrot cake’, ‘spagetti’]
- 元组(不可变的列表)
dimensions=(200,50)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)#要修改就是重新赋值
dimensions=(400,50)
print("\nModifiled dimensions:")
for dimension in dimensions:
print(dimension)
Original dimensions:
200
50Modifiled dimensions:
400
50
- if语句
没有括号有冒号
在if语句作为条件表达式时,Python将在列表至少包含一个元素时返回True,为空时返回false
avaliable_toppings=['a','b','c','d']
requested_toppings=['a','c','e']
for requested_topping in requested_toppings:if requested_topping in avaliable_toppings:print(f"Adding {requested_topping}.")else:print(f"Sorry we don't have {requested_topping}")print("Your pizza is ready!")
Adding a.
Adding c.
Sorry we don’t have e
Your pizza is ready!
0224
- 键值对添加,修改,删除
alient_0={'color':'green'}
print(alient_0)
alient_0['points']=5
alient_0['x_position']=0
alient_0['y_position']=10
print(alient_0)
alient_0['color']='red'
print(f"The alient looks like {alient_0['color']}")
alient_0['speed']='slow'
#向右移动外星人
#根据当前速度决定移动距离
if alient_0['speed']=='slow':x_increment=1;
elif alient_0['speed']=='medium':x_increment=2;
else:x_increment=3;#新位置=原位置+位移
alient_0['x_position']=alient_0['x_position']+x_increment
print(f"New x_position:{alient_0['x_position']}")del alient_0['color']
print(alient_0)
{‘color’: ‘green’}
{‘color’: ‘green’, ‘points’: 5, ‘x_position’: 0, ‘y_position’: 10}
The alient looks like red
New x_position:1
{‘points’: 5, ‘x_position’: 1, ‘y_position’: 10, ‘speed’: ‘slow’}
一开始也可以直接设置空字典
删除的键值对会永远消失
- 由类似对象组成的字典
favorite_languages={'jen':'python','sarah':'c','edward':'ruby','phil':'python',
}
language=favorite_languages['sarah'].title()
print(f"Sarah's favortie language is {language}")
Sarah’s favortie language is C
- 用get()访问值
直接取值,若值不存在会造成编译错误
但是如果使用get()函数可以在键值不存在时返回默认语句,从而避免错误
del alient_0['color']
point_value = alient_0.get('color','No color value assigned!')
print(point_value)
{‘color’: ‘green’}
{‘color’: ‘green’, ‘points’: 5, ‘x_position’: 0, ‘y_position’: 10}
The alient looks like red
New x_position:1
No color value assigned!
- 字典遍历
favorite_languages={'jen':'python','sarah':'c','edward':'ruby','phil':'python',
}for name in favorite_languages.keys():print(name.title())
#因为遍历字典时会默认遍历所有的键,所以将.keys()省略的结果是一样的
for name in favorite_languages:print(name.title())
Jen
Sarah
Edward
Phil
Jen
Sarah
Edward
Phil
favorite_languages={'jen':'python','sarah':'c','edward':'ruby','phil':'python',
}
friends=['phil','sarah']
for name in favorite_languages.keys():print(f"Hi {name.title()}.")if name in friends:language = favorite_languages[name].title()print(f"\t{name.title()}, I see you love {language}!")
Hi Jen.
Hi Sarah.
Sarah, I see you love C!
Hi Edward.
Hi Phil.
Phil, I see you love Python!
- 按照特定的顺序遍历
favorite_languages={'jen':'python','sarah':'c','edward':'ruby','phil':'python',
}
for name in sorted(favorite_languages.keys()):
Edward, thank you for taking the poll
Jen, thank you for taking the poll
Phil, thank you for taking the poll
Sarah, thank you for taking the poll
- 遍历所有值
set集合保证每个元素都是独一无二的
favorite_languages={'jen':'python','sarah':'c','edward':'ruby','phil':'python',
}
supposed_members=['jen','edward','jourlin']
for name in supposed_members:if name in favorite_languages.keys():print(f"Hi {name.title()}, thanking you for taking the poll")else:print(f"Hi {name.title()}, Do you want to have a quit?")
Hi Jen, thanking you for taking the poll
Hi Edward, thanking you for taking the poll
Hi Jourlin, Do you want to have a quit?
- 嵌套——字典列表
alient_0={'color':'green','points':5}
alient_1={'color':'yellow','points':10}
alient_2={'color':'red','points':15}alients=[alient_0,alient_1,alient_2]
for alien in alients:print(alien)
{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘yellow’, ‘points’: 10}
{‘color’: ‘red’, ‘points’: 15}
使用range自动生成
#创建用于存储外星人的空列表
aliens=[]#创建30个绿色的外星人
for alien_number in range(30):new_alien={'color':'green','points':5,'speed':'slow'}aliens.append(new_alien)#切片显示前5个外星人
for alien in aliens[:5]:print(alien)#显示创建了多少个外星人
print(f"The total number of aliens is {len(aliens)}")#修改前3个外星人的属性
for alien in aliens[:3]:if alien['color']=='green':alien['color']='yellow'alien['points']=10alien['speed']='medium'#切片显示前5个外星人
for alien in aliens[:5]:print(alien)
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
The total number of aliens is 30
{‘color’: ‘yellow’, ‘points’: 10, ‘speed’: ‘medium’}
{‘color’: ‘yellow’, ‘points’: 10, ‘speed’: ‘medium’}
{‘color’: ‘yellow’, ‘points’: 10, ‘speed’: ‘medium’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
- 字典中存储列表
#存储点的披萨的信息
pizza={'crust':'thick','toppings':['mushrooms','extra cheese'],
}#概述所点的披萨
print(f"You ordered a {pizza['crust']}-crust pizza ""with the following toppings:")for topping in pizza['toppings']:print("\t"+topping)
You ordered a thick-crust pizza with the following toppings:
mushrooms
extra cheese
favorite_languages={'jen':['python','ruby'],'sarah':['c'],'edward':['ruby','go'],'phil':['python','haskell'],
}
for name, languages in favorite_languages.items():print(f"\n{name.title()}'s favorite languages are:")for language in languages:print(f"\t{language.title()}")
Jen’s favorite languages are:
Python
RubySarah’s favorite languages are:
CEdward’s favorite languages are:
Ruby
GoPhil’s favorite languages are:
Python
Haskell
- 字典中存字典
users={'aeinstein':{'first':'albert','last':'eninsten','location':'princeton',},'mcurie':{'first':'marie','last':'curie','location':'paris',},
}for username, user_info in users.items():print(f"\nUsername: {username}")full_name=f"{user_info['first']} {user_info['last']}"location=user_info['location']print(f"\tFull name:{full_name.title()}")print(f"\tLocation:{location.title()}")
Username: aeinstein
Full name:Albert Eninsten
Location:PrincetonUsername: mcurie
Full name:Marie Curie
Location:Paris
- 在列表间移动元素
#首先创建待验证用户列表
#和一个用于存储已验证用户的空列表
unconfirmed_users=['alice','brain','candace']
confirmed_users=[]#验证每个用户,直到没有未验证用户为止
#将每个经过验证的用户都移到已验证用户列表中
while unconfirmed_users:current_user=unconfirmed_users.pop()print(f"Verifing 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())
Verifing user:Candace
Verifing user:Brain
Verifing user:AliceThe following users have been confirmed:
Candace
Brain
Alice
- 使用用户输入填充字典
responses = {}#设置一个标志,指出调查是否继续
polling_active = Truewhile 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 persn respond? (yes/no)")if repeat=='no':polling_active=False#调查结束,显示结果
print("\n--- Poll Results ---")
for name, response in responses.item():print(f"{name} would like to climb {response}")
0225
- 函数
- 位置实参
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')
#多次调用函数
describe_pet('dog','fluffy')
I have a hamster.
My hamster’s name is HarryI have a dog.
My dog’s name is Fluffy
位置实参的顺序很重要
- 关键字实参
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')
describe_pet(pet_name='harry',animal_type='hamster')
I have a hamster.
My hamster’s name is HarryI have a hamster.
My hamster’s name is Harry
- 函数默认值
有默认值的形参应该放到后面,否则传入的实参还是会以位置参数的形式传给了形参
def describe_pet( pet_name,animal_type='dog'):"""显示宠物的信息"""print(f"\nI have a {animal_type}.")print(f"My {animal_type}'s name is {pet_name.title()}")describe_pet('harry')
I have a dog.
My dog’s name is Harry
如果一个函数的参数中含有默认参数,则这个默认参数后的所有参数都必须是默认参数,否则会报错:SyntaxError: non-default argument follows default argument de…
- 返回简单值
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('jimi','hendrix','lee')
print(musician)
musician = get_formatted_name('jimi','hendrix')
print(musician)
Jimi Lee Hendrix
Jimi Hendrix
- 返回字典
def built_person(first_name, last_name,age=None):"""返回一个字典,其中包含有关一个人的信息"""person={'first':first_name, 'last':last_name}if age:person['age']=agereturn person musician= built_person('jimi', 'hendrix',age=27)
print(musician)
{‘first’: ‘jimi’, ‘last’: ‘hendrix’, ‘age’: 27}
- 加上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':breakl_name=input("Last name: ")if l_name=='q':breakformatted_name=get_formatted_name(f_name,l_name)print(f"\nHello, {formatted_name}")
def make_album(singer, name, number=None):album={'singer_name':singer,'album_name':name}if number:album['number']=numberreturn album while True:print("\nPlease input the singer's name, album's name: ")print("enter 'q' at any time to quit.")s_name=input("Singer's name: ")if s_name=='q':breaka_name=input("Album's name: ")if a_name=='q':breakalbum_information=make_album(s_name,a_name)print(f"\n {album_information}")
Please input the singer’s name, album’s name:
enter ‘q’ at any time to quit.
Singer’s name: Ariana Grande
Album’s name: Dangerous Woman{‘singer_name’: ‘Ariana Grande’, ‘album_name’: ‘Dangerous Woman’}
Please input the singer’s name, album’s name:
enter ‘q’ at any time to quit.
Singer’s name: Maroon 5
Album’s name: Overexposure{‘singer_name’: ‘Maroon 5’, ‘album_name’: ‘Overexposure’}
Please input the singer’s name, album’s name:
enter ‘q’ at any time to quit.
Singer’s name: q
- 传递列表
def greet_users(names):"""向列表中的每位用户发出简单的问候"""for name in names:msg=f"Hello, {name.title()}!"print(msg)usernames=['hannah','ty','margot']
greet_users(usernames)
Hello, Hannah!
Hello, Ty!
Hello, Margot!
- 函数中修改列表
普通方法
#首先创建一个列表,其中包含一些要打印的设计
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_model)
函数法
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)
Printing model:dodecahedron
Printing model:robot pendant
Printing model:phone case
The following models have been printed:
dodecahedron
robot pendant
phone case
写成函数更容易扩展和维护
- 课后小题,禁止函数修改列表
text_info=['hello','sorry','fresh','man']
completed=[]
def show_messages(texts):for text in texts:print(text)show_messages(text_info)
print(text_info)def send_messages(texts):while texts:current=texts.pop()print(current)completed.append(current)send_messages(text_info[:])
print(text_info)
print(completed)
hello
sorry
fresh
man
[‘hello’, ‘sorry’, ‘fresh’, ‘man’]
man
fresh
sorry
hello
[‘hello’, ‘sorry’, ‘fresh’, ‘man’]
[‘man’, ‘fresh’, ‘sorry’, ‘hello’]
- 结合使用位置实参和任意数量实参
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(16,'pepperoni')
make_pizza(12,'mushrooms','green peppers','extra cheese')
Making a 16-inch pizza with the following toppings:
-pepperoniMaking a 12-inch pizza with the following toppings:
-mushrooms
-green peppers
-extra cheese
经常看到*arg收集任意数量的位置实参
- 使用任意数量的关键字实参
def build_profile(first, last, **user_info):"""创建一个字典,其中包含我们知道的关于用户的一切"""user_info['first_name']=firstuser_info['last_name']=lastreturn user_infouser_profile=build_profile('albert','einstein',location='princeton',field='physics')
print(user_profile)
{‘location’: ‘princeton’, ‘field’: ‘physics’, ‘first_name’: ‘albert’, ‘last_name’: ‘einstein’}
经常看到**kwargs收集任意数量的关键字实参
0227
类
class Dog:"""一次模拟小狗的简单尝试"""def __init__(self, name, age):"""初始化属性"""self.name = nameself.age = agedef sit(self):"""模拟小狗收到命令时蹲下"""print(f"{self.name} is now sitting.")def roll_over(self):"""模拟小狗收到命令时打滚"""print(f"{self.name} rolled over!")
- 方法_init_()
- 类中的函数被称为方法,根据类创建新实例时,会自动运行该方法。开头末尾都有双下划线!!!!!!!,是避免与其他函数名产生冲突
- self必须存在且位于其他形参的前面,是一个指向实例本身的引用,让实例能够访问类中的属性和方法,每当创建一个新的实例时,只需要给除self外的其他形参提供值即可
- name和age都有前缀self,以self为前缀的变量可供类中的所有方法使用,这样可以通过实例访问的变量称为属性
- 根据类创建实例
class Dog:--snip--my_dog= Dog('Willie',6)print(f"My dog's name is {my_dog.name}.")
print(f"My dog is {my_dog.age} years old.")
My dog’s name is Willie.
My dog is 6 years old.
- 调用方法
my_dog.sit()
my_dog.roll_over()
Willie is now sitting.
Willie rolled over!
- 给属性指定默认值
不用在函数中声明一个新的形参,直接在定义中添加属性
def __init__(self, make, model, year):"""初始化描述汽车的属性"""self.make = makeself.model=modelself.year=yearself.odometer_reading = 0
- 修改属性的值
- 直接修改属性的值
my_new_car.odometer_reading=23
- 通过方法修改属性的值
def update_odometer(self, mileage):self.odometer_reading = mileagemy_new_car.read_odometer(12)
- 通过方法对属性的值进行递增
def increment_odometer(self, miles):self.odometer_reading += miles
餐厅作业
class Restaurant:def __init__(self, restaurant_name, cuisine_type):self.restaurant_name=restaurant_nameself.cuisine_type=cuisine_typeself.number_served=0def describe_restaurant(self):print(f"\nWe are {self.restaurant_name}, we offer {self.cuisine_type} type food")def open_restaurant(self):print("We are opening~")def read_number(self):print(f"{self.number_served} people have came to {self.restaurant_name}")def set_number_served(self, number):self.number_served = numberdef increment_number_served(self, increase):self.number_served+=increaserestaurant_1=Restaurant('Song Hotpot','Hotpot')
restaurant_1.describe_restaurant()
restaurant_1.open_restaurant()restaurant_2=Restaurant('Tah','taiguocai')
restaurant_2.describe_restaurant()restaurant_3=Restaurant('Malubianbian','BBQ')
restaurant_3.describe_restaurant()restaurant_1.read_number()
restaurant_1.number_served=23
restaurant_1.read_number()restaurant_2.read_number()
restaurant_2.set_number_served(14)
restaurant_2.read_number()restaurant_3.read_number()
restaurant_3.increment_number_served(225)
restaurant_3.read_number()
We are Song Hotpot, we offer Hotpot type food
We are opening~We are Tah, we offer taiguocai type food
We are Malubianbian, we offer BBQ type food
0 people have came to Song Hotpot
23 people have came to Song Hotpot
0 people have came to Tah
14 people have came to Tah
0 people have came to Malubianbian
225 people have came to Malubianbian
- 继承
特殊函数super()能够调用父类的方法
class User:def __init__(self, first_name, last_name, gender, hobby):self.first_name=first_nameself.last_name=last_nameself.gender=genderself.hobby=hobbydef describe_user(self):print(f"Name - {self.first_name.title()} {self.last_name.title()}")print(f"Is a {self.gender.title()}. Hobby is {self.hobby}")def greet_user(self):print(f"Hello~ {self.first_name}")class Privileges:def __init__(self):self.privileges=['can add post','can delete post','can ban user']def show_privileges(self):print(f"ADMIN can do things like {self.privileges}.")class Admin(User):def __init__(self, first_name, last_name, gender, hobby):super().__init__(first_name, last_name, gender, hobby)self.privilege = Privileges()admin_user=Admin('ziqi','yin','female','dance')
admin_user.privilege.show_privileges()
ADMIN can do things like [‘can add post’, ‘can delete post’, ‘can ban user’].
- 导入类
0228
- 文件和异常
- 读取文件路径使用斜杠或者双反斜杠
- for line in file_name可用于遍历循环
"""读取整个文件"""
filename = 'learning_python.txt'
with open(filename) as file_object:contents = file_object.read()print(contents.rstrip())"""遍历文件对象"""
with open(filename) as file_object:for line in file_object:print(line.rstrip())"""存储在列表中"""
with open(filename) as file_object:lines = file_object.readlines()for line in lines:print(line.rstrip())
In Python you can liebiao
In Python you can shuzu
In Python you can zidian
In Python you can hanshu
In Python you can liebiao
In Python you can shuzu
In Python you can zidian
In Python you can hanshu
In Python you can liebiao
In Python you can shuzu
In Python you can zidian
In Python you can hanshu
- 10.2替换
filename = 'learning_python.txt'
"""存储在列表中"""
with open(filename) as file_object:lines = file_object.readlines()for line in lines:line=line.rstrip()print(line.replace('Python','C'))
In C you can liebiao
In C you can shuzu
In C you can zidian
In C you can hanshu
- 调用open()时的实参
第一个是打开的文件名称,第二个是模式,读取’r’,写入’w’,附加’a’,读写模式’r+‘。忽略的话将以默认的只读模式打开文件
filename = 'programming.txt'
##写入多行
with open(filename, 'w') as file_object:file_object.write("I love programming.\n")file_object.write("I love creating new games\n")##附加到文件
with open(filename, 'a') as file_object:file_object.write("I also love finding meaning in large datasets.\n")file_object.write("I love creating apps that can run in a browser.\n")
I love programming
I love creating new games
- 10_4
filename = 'guest_book.txt'
while True:guest_name = input("Please tell me your name: (Enter 'quit' when you are finished.)")if guest_name == 'quit':breakelse:print(f"\nHello~ {guest_name}")with open(filename, 'a') as file_object:file_object.write(guest_name+" has come here\n")
- 10_6
print("Give me two numbers and I'll give you the summary")
first_number=input("\nFirst number:")
second_number=input("\nSecond number:")
try:sum=int(first_number)+int(second_number)
except ValueError:print("Please input number!")
else:print(sum)
- json.dump()
import json
numbers = [2,3,4,7,11,13]
filename = 'numbers.json'
with open(filename,'w') as f:json.dump(numbers,f)
参数1:要存储的数据
参数2:用于存储数据的文件对象
- json.load()
将列表读取到内存中:
import jsonfilename='numbers.json'
with open(filename) as f:numbers = json.load(f)print(numbers)
- 测试
#导入了模块和要测试的函数
import unittest
from name_function import get_formatted_name#创建的NameTestCase类用于包含一系列针对get_formatted_name()的单元测试
#必须继承unittest.TestCase才说明是测试类
class NamesTestCase(unittest.TestCase):"""测试name_function.py"""def test_first_last_name(self):"""能够正确的处理像Janis Joplin这样的姓名吗?"""formatted_name = get_formatted_name('janis','joplin')#使用了断言方法,核实得到的结果是否与期望的结果一致self.assertEqual(formatted_name,'Janis Joplin')#检查特殊变量__name__,是程序执行时设置的
#如果该文件作为主程序执行,变量name将被设置为main,调用unittest.main()来运行测试用例
#如果该文件被测试框架导入,变量__name__的值将不会是main,因此不会调用unittest.main()
if __name__=='__main__':unittest.main()
.
---------------------------—----------------------------------------—
Ran 1 test in 0.000s
OK