Python 编程从入门到实践3
2018-04-01 本文已影响0人
蜘蛛的梦呓
8.1 定义函数
关键词:def
文档字符串: '''str'''
传递实参的方式:
1.位置实参
2.关键字实参
3.默认值
4.混合使用
8.3.2 让实参变成可选
给实参指定一个默认值 - 空字符串,并将这个实参一道形参列表的末尾,这样可以使实参变成可选。
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()
# 位置实参
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
musician = get_formatted_name('john', 'hooker', 'lee')
print(musician)
>>> Jimi Hendrix
>>> John Lee Hooker
>>> {'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton'}
8.3.4 结合使用函数和while循环
def get_formatted_name(first_name, last_name):
'''返回整洁的姓名'''
full_name = first_name + ' ' + last_name
return full_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 + '!')
8.5传递任意数量的实参
def make_prizza(*toppings):
print(toppings)
make_prizza('pepperoni')
make_prizza('mushrooms', 'green peppers', 'extra cheese')
>>> ('pepperoni',)
>>> ('mushrooms', 'green peppers', 'extra cheese')
8.5.2使用任意数量的关键字实参
将函数变成成能接受任意数量的键 - 值对
def build_profile(first, last, **urser_info):
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key, value in urser_info.items():
profile[key] = value
return profile
user_profile = build_profile('albert', 'einstein', location='princeton', field='physics')
print(user_profile)
>>> {'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton'}
9.1创建和使用类
class Dog():
# __init__() 方法:每当一个类创建新实例时, python 都会自动运行它
def __init__(self, name, age):
self.name = name
self.age = age
def sit(self):
# 模拟小狗被命令蹲下
print(self.name.title() + 'is now sitting')
#9.1.2 根据类创建一个实例
my_dog = Dog('willie','6')
#访问属性
print(my_dog.name.title() + ',' +my_dog.age)
#调用方法
my_dog.sit()
>>> Willie,6
>>> Willieis now sitting
9.2.3修改属性的值
class Car():
def __init__(self, make):
self.make = make
# 给属性指定默认值
self.odmeter_reading = 0
# 打印车辆信息
def read(self):
print('This ' + self.make.title() + ' has ' + str(self.odmeter_reading) + ' miles on it')
def update_odometer(self, mileage):
# 将里程表读数设置为指定的值
self.odmeter_reading = mileage
my_new_car = Car('audi')
# 1.直接修改属性
my_new_car.odmeter_reading = 23
my_new_car.read()
# 2.通过方法修改属性
my_new_car.update_odometer(25)
my_new_car.read()
>>> This Audi has 23 miles on it
>>> This Audi has 25 miles on it
9.3继承
#括号中添加所要继承的父类
class ElectricCar(Car):
# 电动汽车的独特之处
def __init__(self, make):
# 初始化父类的属性
super().__init__(make)
# 1.添加子类特有属性以及方法
self.battery_size = 70
def describe_battery(self):
# 打印出电瓶容量的消息
print('This ' + self.make.title() + ' has a ' + str(self.battery_size) + '-kwh battery.')
#2.重写方法
def read(self):
print('这是一辆电动汽车')
my_tesla = ElectricCar('tesla')
my_tesla.read()
>>> 这是一辆电动汽车
>>> This Tesla has a 70-kwh battery.
10.1 从文件中获取数据
10.0.1 读取整个文件
with open('digits.txt')as file_object:
# 逐行读取
for line in file_object:
# 每行末尾都有一个看不见的换行符,使用 rstrip() 去掉空行
print(line.rstrip())
# contents = file_object.read()
# print(contents)
10.2 写入文件
with open('text.txt', 'w')as file_object:
# w:写入模式 a:追加模式 r:读取模式 r+:可读可写模式
file_object.write('I love python')
# 注意 Python 只能将字符串写入文件文件,写入数字必须先使用 str() 将其转换为字符串
10.4存储数据
10.4.1 使用 json.dump() 和 json.load()
import json
numbers = [2, 3, 4]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
# json.dump() 接受 2 个数据:1.数据 2.文件位置
json.dump(numbers, f_obj)
# 使用json.load() 将列表读取到内存中
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)
综合使用
# 如果以前存储了用户名,就加载它
# 否则,就提示用户输入用户名并保存它
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input('What is your name?')
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print('we will remember you, ' + username + '!')
else:
print('Welcome back, ' + username + '!')