1 关于类的导入
可以把类封装到1个文件中
1个文件中也可以封装多个类
在导入的时候可以导入单个,也可以导入多个类,也可以全部导入类
car.py
"""一个可以用于表示汽车的类""" 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): self.odometer_reading = mileage def increment_odometer(self,miles): self.odometer_reading += miles 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.") def fill_gas_tank(self): print("This is OK!") 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.") def get_range(self): if self.battery_size == 70: range = 240 elif self.battery_size == 85: range = 270 message = "This car can go approximately " + str(range) message +=" miles on a full charge" print(message)
import car 导入整个模块
from car import * 导入所有的类
对于互相依赖的类,导入的时候记得 前后顺序
2 PYTHON标准库
OrderedDict 可以记录 字典的 键值添加顺序
from collections import OrderedDict favorite_languages = OrderedDict() favorite_languages['jen'] = 'python' favorite_languages['sarah'] = 'c' favorite_languages['edward'] = 'ruby' favorite_languages['phil'] = 'python' for name,language in favorite_languages.items(): print(name.title() + "'s favorite language is " + language.title() + ".")
3 关于编写类的编码风格
类的命名 使用驼峰风格 实例和模块名使用小写并且单词之间加下划线
关于空行也要谨慎使用