9 类
面向对象编程 根据类来创建对象称为实例化
类名 首字母大写 每次创建新的实例时运行 init() 方法,其中形参self必不可少,且位于其他形参之前
class Dog():
"""一次模拟小狗的简单尝试"""
def __init__(self,name, age):
"""初始化属性name age"""
self.name = name
self.age = age
def sit(self):
"""模拟小狗被命令蹲下"""
print(self.name.title() + " is now sitting.")
def roll_over(self):
"""模拟小狗被命令打滚"""
print(self.name.title() + " rolled 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.name
my_dog.sit()
9.2 使用类和实例
修改实例的属性
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 = str(self.year) + ' ' + self.make + ' ' +self.model
return long_name.title()
def read_odometer(self):
"""打印一条汽车里程的消息"""
print("This car has " + str(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
my_new_car = Car('audi' , 'a4' , 2016)
print(my_new_car.get_descriptive_name())
my_new_car.odometer_reading = 23 #直接修改属性
my_new_car.update_odometer(23) #通过方法修改属性
my_new_car.increment_odometer(100) #通过方法对属性增加
my_new_car.read_odometer()
9.3 继承
原有的类称为父类,新类称为子类
class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self, make, model, year):
"""初始化父类的属性"""
super().__init__(make, model, year)
self.battery_size = 70
def describe_battery(self):
"""打印一条描述电瓶容量的消息"""
print("This car has a " +str(self.battery_size) + "-kwh battery.")
super()关联父类,父类也叫超类(superclass)
重写父类的方法(覆盖掉fill_gas_tank()方法)
class ElectricCar(car):
--snip--
def fill_gas_tank():
"""电动车没有邮箱"""
print("This car doesn't need a gas tank!")
9.4导入类
from car import Car
from car import Car, ElectricCar #导入多个类 类后面没有括号
import car #导入整个模块,引用时用点号
from module_name import * #导入模块中的所有类,可能引起名称冲突,不建议用
9.5 标准库
from collections import OrderedDict
favorite_languages = OrderedDict() #有序字典
favorite_languages['jen'] = 'python'
favorite_languages['sarah'] = 'c'
9.6 类编码风格
类名采用驼峰命名法 ,即将类名中的每个单词的首字母都大写,而不使用下划线。实例名和模块名都采用小写格式,并在单词之间加上下划线。
对于每个类,都应紧跟在类定义后面包含一个文档字符串,简要地描述类的功能。每个模块也都应包含一个文档字符串,对其中的类可用于做什么进行描述。
需要同时导入标准库中的模块和你编写的模块时,先编写导入标准库模块的import语句,再添加一个空行,然后编写导入你自己编写的模块的import语句。
10 文件和异常
with open('pi_digits.txt') as file_object:
contents = file_objetc.read()
print(contents)
文件名相对路径
在Linux和OS X中,你可以这样编写代码:
with open(‘text_files/filename.txt’) as file_object:
Windows系统中,在文件路径中使用反斜杠(\)而不是斜杠(/):
with open(‘text_files\filename.txt’) as file_object:
文件名绝对路径
在Linux和OS X中,绝对路径类似于下面这样:
file_path = ‘/home/ehmatthes/other_files/text_files/filename.txt’
with open(file_path) as file_object:
而在Windows系统中,它们类似于下面这样:
file_path = ‘C:\Users\ehmatthes\other_files\text_files\filename.txt’
with open(file_path) as file_object:
#逐行读取
filename = 'pi_digits.txt'
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())
#构造一个包含文件内容的字符串
for line in lines:
pi_string += line.strip()
print(pi_string)
with open(filename, 'w') as file_object:
file_object.write("I love programming!")
open第二个参数读取(‘r’),写入(“w”),附加(“a”),读写(“r+”)
10.3 异常
try:
print(4/0)
except ZeroDivisionError:
print("You can't divide by zero")
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
second_number = input("Second number: ")
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by 0!")
else:
print(answer)
pass,在代码中占位什么都不做
10.4 json
dump() load()
import json
numbers = [2,3,4,5,6,7]
filename = 'number.json'
#转为json并写入文件
with open(filename,'w') as f_obj:
json.dump(numbers , f_obj)
#读取json到列表
with open(filename , 'r') as f_obj:
numbers_read = json.load(f_obj)
print(numbers_read)
将代码划分为一系列完成具体工作的函数的过程被称为重构。重构让代码更清晰、更易于理解、更容易扩展。