类模板
类模板由来:为了简化主程序,可以将部分类拆分放到类模板中。
类模板的定义: 类的定义变量名首字母大写;类模板文件名小写,后缀名为.py
类模板的导入包括以下几个方式
1、导入单个类
2、从一个模块中导入多个类
3、导入整个模块
4、导入模块中的所有类
5、在一个模块中导入另一个模块
6、Python标准库 collections 中的OrderedDict类
开些之前,我先把需要用到的类模板放到下面
1.1、car类模板
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 15 20:34:36 2023
@author: USUS
"""
class Car():
"""一次魔力汽车的简单尝试"""
def __init__(self,make,model,year):
"""初始化描述汽车的属性"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 ## 添加一个随时间变化的属性
# 更新里程属性的方法
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
def get_describle_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.")
class Battery():
"""
一次模拟电动汽车电瓶的简单尝试
"""
def __init__(self,battery_size = 70):
"""初始化电瓶属性"""
self.battery_size = battery_size
def describle_battery(self):
"""打印一条描述电瓶容量的消息"""
print("This car has a "+ str(self.battery_size) + "-KWh battery.")
def get_range(self):
"""打印一条描述电瓶车容量的消息"""
if self.battery_size == 70:
ranges = 240
elif self.battery_size == 85:
ranges = 270
message = "This car can go approximately " + str(ranges)
message += " miles on full charge."
print(message)
class ElectricCar(Car):
"""模拟电动车的独特之处"""
def __init__(self, make, model, year):
"""
初始化父类的属性,再初始化电动汽车特有的属性
"""
super().__init__(make, model, year)
self.battery = Battery()
1.2 car1类模板
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 18 18:32:07 2023
@author: USUS
"""
class Car():
"""一次魔力汽车的简单尝试"""
def __init__(self,make,model,year):
"""初始化描述汽车的属性"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 ## 添加一个随时间变化的属性
# 更新里程属性的方法
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
def get_describle_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.")
1.3 electric_car1类模板
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 18 18:32:45 2023
@author: USUS
"""
class Battery():
"""
一次模拟电动汽车电瓶的简单尝试
"""
def __init__(self,battery_size = 70):
"""初始化电瓶属性"""
self.battery_size = battery_size
def describle_battery(self):
"""打印一条描述电瓶容量的消息"""
print("This car has a "+ str(self.battery_size) + "-KWh battery.")
def get_range(self):
"""打印一条描述电瓶车容量的消息"""
if self.battery_size == 70:
ranges = 240
elif self.battery_size == 85:
ranges = 270
message = "This car can go approximately " + str(ranges)
message += " miles on full charge."
print(message)
from car1 import Car #从car1模板中导入Car这个类,需要先声明否则会报错,也可在最开头导入,相当于C++中,函数的先声明一样
class ElectricCar(Car):
"""模拟电动车的独特之处"""
def __init__(self, make, model, year):
"""
初始化父类的属性,再初始化电动汽车特有的属性
"""
super().__init__(make, model, year)
self.battery = Battery()
下面进入实际操作
1、导入单个类
from car import Car # 从car类模板中导入Car类
my_new_car = Car('audi','a4',2016) # 实例化对象
print(my_new_car.get_describle_name()) # 调用对象的方法
my_new_car.odometer_reading = 23 # 更改对象的属性
my_new_car.read_odometer() # 调用对象的方法
结果:
2016 Audi A4
This car has 23 miles on it.
2、从一个模块中导入多个类
## 9-4-2 在一个模块中导入多个类
from car import Car,ElectricCar # 从car类模板中导入Car,ElectricCar两个类
my_bettle = Car('volkswagen', 'beetle', 2016) # 创建对象,叫做实例化
print(my_bettle.get_describle_name()) # 调用对象的方法
my_tesla = ElectricCar('tesla', 'roadster', 2016) # 创建对象,叫做实例化
print(my_tesla.get_describle_name()) # 调用对象的方法
结果:
2016 Volkswagen Beetle
2016 Tesla Roadster
3、导入整个模块
import car # 导入car类模板中的所有类
my_bettle = car.Car('volkswagen', 'beetle', 2016) # 创建对象
print(my_bettle.get_describle_name()) # 调用对象方法
my_tesla = car.ElectricCar('tesla', 'roadster', 2016) # 创建对象
print(my_tesla.get_describle_name()) # 调用对象方法
结果:
2016 Volkswagen Beetle
2016 Tesla Roadster
4、导入模块中的所有类
方法:from module_name(模板名) import *
from car import * # 从car类模板中导入所有类
my_bettle = Car('volkswagen', 'beetle', 2016) # 创建对象,实例化
print(my_bettle.get_describle_name()) # 调用对象方法
my_tesla = ElectricCar('tesla', 'roadster', 2016) # 创建对象,实例化
print(my_tesla.get_describle_name()) # 调用对象方法
结果:
2016 Volkswagen Beetle
2016 Tesla Roadster
5、在一个模块中导入另一个模块
前提:导入另一个模块需要先从模块中导入,然后到入后面的模块
即前面一个模块是后面一个模块的父类
适用场合:大项目开发
注意需要在子类中使用 from parent_module import parent_class 从父类板中导入类,否则报错
from car1 import Car # 先导入Car父类模块
from electric_car1 import ElectricCar # 在导入子类模块
my_bettle = Car('volkswagen', 'beetle', 2016)
print(my_bettle.get_describle_name())
my_tesla = ElectricCar('tesla', 'roadster', 2016)
print(my_tesla.get_describle_name())
结果:
2016 Volkswagen Beetle
2016 Tesla Roadster
6、Python标准库 collections 中的OrderedDict类 ## 模块collection 中: OrderedDict类
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())
结果:
Jen's favorite language is Python
Sarah's favorite language is C
Edward's favorite language is Ruby
Phil's favorite language is Python
总结: 类模板的导入可以导入单个类、多个类、或者一起导入
希望各行各业的同志们,像对待每一位好老师有恭敬心一样,恭敬每一本好书,这样你们将从中获德益处。
版权声明:本文为qq_45357184原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。