学习内容1
- 基本函数的构成:定义、实现和调用函数参数,函数返回值。 (第八章)
#位置实参,顺序很重要
def describe_pet(animal_type, pet_name = 'ami'):
#可在函数列表中指定默认值,放在后面
"""显示宠物信息"""
print("\nI have a "+animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet('hamster','harry')
#关键字实参,位置顺序无关
describe_pet(animal_type='hamster',pet_name='harry')
describe_pet(pet_name='harry',animal_type='hamster')
#使用默认值
describe_pet('dog')
#返回值
def city_country(city_name,country_name):
citycountry = city_name.title() + ', '+ country_name.title()
return citycountry
citycountry = city_country('changsha','china')
print("\n"+ citycountry)
#返回字典
def buiding_person(first_name,last_name,age = ''):
person = {'first': first_name,'last': last_name}
if age:
person['age'] = age
return person
musician = buiding_person('Fang','Yujie',24)
print(musician)
结果:
I have a hamster.
My hamster's name is Harry.
I have a hamster.
My hamster's name is Harry.
I have a hamster.
My hamster's name is Harry.
I have a dog.
My dog's name is Ami.
Changsha, China
{'first': 'Fang', 'last': 'Yujie', 'age': 24}
- 函数内部变量的作用域,可以通过locals()和globals()两个函数来了解。(第八章)
'''定义在函数内部的变量拥有一个局部作用域,定义在函数外的拥有全局作用域。
局部变量只能在其被声明的函数内部访问,而全局变量可以在整个程序范围内访问。
调用函数时,所有在函数内声明的变量名称都将被加入到作用域中。'''
total = 0 # 这是一个全局变量
def sum(arg1, arg2):
# 返回2个参数的和.
total = arg1 + arg2 # total在这里是局部变量.
print("函数内是局部变量 : ", total)
return total
# 调用sum函数
sum(10, 20)
print("函数外是全局变量 : ", total)
结果:
函数内是局部变量 : 30
函数外是全局变量 : 0
- 匿名函数:lambda,了解map函数,并用lambda完成列表(注:列表中各个元素全为数字类型)中每一个元素+1的操作。
lambda语法:lambda [arg1 [,arg2,…argn]]:expression
map用法:map()
s = list(map(lambda a:a+1,[1,2,3]))
print(s)
结果:
[2, 3, 4]
- 了解文件操作,如何写入,读取,追加,并了解读取文件中每一行的几种方式。(第十章)
#with open('Files\pi.txt') as file_object: #需先打开文件才能访问open(),相对路径读取
file_path = 'D:\Python_text\Files\pi.txt' #绝对路径读取,r是为了避免与转义字符混淆
with open(file_path) as file_object:
contents = file_object.read() #读取文件
print(contents.rstrip()) #打印并删除空行
结果:
3.1415926535
8979323846
2643383279
#逐行读取
#方法1
filename = 'pi.txt'
with open(filename) as file_object:
for line in file_object:
print(line)
#方法2
filename = 'pi.txt'
with open(filename) as file_object:
lines = file_object.readlines() #存储于列表
for line in lines:
print(line)
结果:
3.1415926535
8979323846
2643383279
3.1415926535
8979323846
2643383279
#写入
filename = 'programming.txt'
with open(filename,'w') as file_object:
file_object.write('I love python!\n')
file_object.write('I love you!\n')
#附加
filename = 'programming.txt'
with open(filename,'a') as file_object:
file_object.write('I love python,too!\n')
file_object.write('I love you,too!\n')
学习内容2
- 创建和使用类(第九章),为什么说python中一切皆对象?,object类代表了什么?
python中一切皆对象https://blog.csdn.net/LRLZ_Python/article/details/49893103
object类在python3.x中默认加载,具体有没有object类的区别可以参见下面博客:object用法
class Dog(): #首字母大写表示类
"""一次模拟小狗的简单尝试"""
def __init__(self,name,age): #形参self位于其他形参前面,且必不可少
"""初始化属性name和age"""
self.name = name #以self为前缀的变量可供所有方法(即函数)使用
self.age = age
def sit(self):
"""模拟小狗被命令时蹲下"""
print(self.name.title() + " is now sitting. ")
def rool_over(self):
"""模拟小狗被命令时打滚"""
print(self.name.title() + " rooled over! ")
#创建和使用类
my_dog = Dog("willie",6)
#访问属性
print("My dog's name is "+ my_dog.name.title()+".")
print("My dog is "+ str(my_dog.age)+ " years old.")
#调用方法
my_dog.sit()
my_dog.rool_over()
结果:
My dog's name is Willie.
My dog is 6 years old.
Willie is now sitting.
Willie rooled over!
- 使用类和实例(第九章),self关键字有什么作用?
self作用:(1)形参self位于其他形参前面,且必不可少。在函数调用中将自动传入实参self 。每个与类相关联的方法调用都自动传递实参self ,它是一个指向实例本身 的引用,让实例能够访问类中的属性和方法。
(2)以self为前缀的变量可供所有方法(即函数)使用。
class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self,make,model,year):
"""初始化"""
self.make = make
self.model = model
self.year = year
self.od_reading = 0 #新增属性值,汽车里程
def get_descriptive_name(self):
"""返回整洁的描述信息"""
long_name = str(self.year)+ " "+ self.make+ " "+ self.model
return long_name.title()
def read_od(self): #读取汽车里程
print("This car has "+ str(self.od_reading)+ " miles on it.")
def update_od(self,mileage): #通过方法更新属性值
"""禁止回调里程"""
if mileage >= self.od_reading:
self.od_reading = mileage
else:
print("You can't rool back an odometer!")
def incremet_od(self,miles): #递增里程
self.od_reading += miles
newcar = Car('audi','a4',2016)
print(newcar.get_descriptive_name())
newcar.od_reading = 15 #直接修改属性值
newcar.read_od()
newcar.update_od(24) #通过方法修改属性值
newcar.read_od()
newcar.incremet_od(100)
newcar.read_od()
结果:
2016 Audi A4
This car has 15 miles on it.
This car has 24 miles on it.
This car has 124 miles on it.
- 继承(第九章)(附加:类中三大特性,封装,继承和多态,c++和java都有多态,python明面上是没有多态的,但是也可以实现,如果有能力,可以探究下如何实现)
class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self,make,model,year):
"""初始化"""
self.make = make
self.model = model
self.year = year
self.od_reading = 0 #新增属性值,汽车里程
def get_descriptive_name(self):
"""返回整洁的描述信息"""
long_name = str(self.year)+ " "+ self.make+ " "+ self.model
return long_name.title()
def read_od(self): #读取汽车里程
print("This car has "+ str(self.od_reading)+ " miles on it.")
def update_od(self,mileage): #通过方法更新属性值
"""禁止回调里程"""
if mileage >= self.od_reading:
self.od_reading = mileage
else:
print("You can't rool back an odometer!")
def incremet_od(self,miles): #递增里程
self.od_reading += miles
def fill_gas_tank(self):
"""加满油箱"""
print("The fuel tank is full")
class Battery():
"""一次模拟电瓶的简单尝试"""
def __init__(self,battery_size=70):
self.battery_size = battery_size
def describe_battery(self): #打印电瓶容量
print("This car has a "+ str(self.battery_size)+ "-kwh battery.")
class ElecCar(Car): #父类位于子类前面,定义子类时括号内指定父类名称
"""电动汽车的独特之处"""
def __init__(self, make, model, year):
"""初始化父类属性"""
super().__init__(make,model,year)
self.battery = Battery() #定义子类特有属性,将实例用作属性
def fill_gas_tank(self): #重写父类
"""加满油箱"""
print("This car doesn't need a gas tank!")
#父类测试
newcar = Car('audi','a4',2016)
print(newcar.get_descriptive_name())
newcar.od_reading = 15 #直接修改属性值
newcar.read_od()
newcar.update_od(24) #通过方法修改属性值
newcar.read_od()
newcar.incremet_od(100)
newcar.read_od()
print("\n",end='')
#继承子类测试
test = ElecCar('tesla','model s','2016')
print(test.get_descriptive_name())
test.fill_gas_tank()
test.battery.describe_battery()
结果:
2016 Audi A4
This car has 15 miles on it.
This car has 24 miles on it.
This car has 124 miles on it.
2016 Tesla Model S
This car doesn't need a gas tank!
This car has a 70-kwh battery.
- import类到其他文件使用的几种方法,并在类中实现一个函数打印__file__关键字,看下__file__前后的变化,并解释原因(第九章)
(1)导入单个类
from 被导入类文件名 import 被导入类名
例如:from car import Car 从文件car.py中导入Car类
(2)导入多个类
from 被导入类文件名 import 被导入类名1,类名2等
例如:from car import Car,ElectricCar
(3)导入整个模块
import 被导入文件名
例如:import car
(4)导入模块内所有类
from car import *
例如:from car import *