Python 学习笔记16 类 - 导入
我们在编码的过程中,可能会给对象添加越来越多的功能,即使我们使用了继承,也不可避免的使文件越来越臃肿。
为了避免这种情况, Python允许将对象存储在模块中,并且可以在其他模块中进行导入。
其实这和C#中的命名空间相类似。
我们首先准备了一个叫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_description_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 cannot do that.") def increase_odometer(self, miles):
if miles >= 0:
self.odometer_reading += miles
else:
print("The value is invalid, please input the number which should more than zero.") def fill_gas(self):
print("Car is filling gas.") '''生成一个电池类'''
class Battery():
def __init__(self, size = 100):
self.size = size def describe_battery(self):
print("Battery has " + str(self.size) + "-kwh battery. " ) def show_range(self):
print("Battery has " + str(self.size * 3) + " killmaters on full charge") '''继承car,生成一个新类'''
class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init__(make, model, year)
self.battery = Battery() def fill_gas(self):
print("Electric car no gas tank.")
接下来我们新建一个my_car的模块,并导入Car类并创建实例,并且调用一些方法:
#-*- coding:utf-8 -*-
from car import Car my_new_car = Car('Volvo', 'V60', '')
print(my_new_car.get_description_name()) my_new_car.odometer_reading = 200
my_new_car.read_odometer() '''
输出:
2020 Volvo V60
This car has 200 miles on it. '''
同样,我们也可以在一个模块里面存储、导入多个类,进行操作:
#-*- coding:utf-8 -*-
from car import Car, ElectricCar my_new_car = Car('Volvo', 'V60', '')
print(my_new_car.get_description_name()) my_new_car.odometer_reading = 200
my_new_car.read_odometer() my_byd_tang = ElectricCar('BYD', 'Tang', '')
my_byd_tang.battery.show_range()
my_byd_tang.fill_gas()
'''
输出:
2020 Volvo V60
This car has 200 miles on it.
Battery has 300 killmaters on full charge
Electric car no gas tank. '''
当然你可以导入模块中的所有的类:
#-*- coding:utf-8 -*-
from car import * my_new_car = Car('Volvo', 'V60', '')
print(my_new_car.get_description_name()) my_new_car.odometer_reading = 200
my_new_car.read_odometer() my_byd_tang = ElectricCar('BYD', 'Tang', '')
my_byd_tang.battery.show_range()
my_byd_tang.fill_gas() my_battery = Battery()
my_battery.show_range()
'''
输出:
2020 Volvo V60
This car has 200 miles on it.
Battery has 300 killmaters on full charge
Electric car no gas tank.
Battery has 300 killmaters on full charge
'''
也可以直接导入整个模块,不过这种方式需要在类的名字前加上模块名:
#-*- coding:utf-8 -*-
import car my_new_car = car.Car('Volvo', 'V60', '')
print(my_new_car.get_description_name()) my_new_car.odometer_reading = 200
my_new_car.read_odometer() my_byd_tang = car.ElectricCar('BYD', 'Tang', '')
my_byd_tang.battery.show_range()
my_byd_tang.fill_gas() my_battery = car.Battery()
my_battery.show_range()
'''
输出:
2020 Volvo V60
This car has 200 miles on it.
Battery has 300 killmaters on full charge
Electric car no gas tank.
Battery has 300 killmaters on full charge
'''
我们在实际的编码过程中,还是比较推荐一个类只定义在单一的模块中,这样模块的大小不会太大,也方便其他模块进行调用。
也方便进行维护。
Python 学习笔记16 类 - 导入的更多相关文章
- python学习笔记4_类和更抽象
python学习笔记4_类和更抽象 一.对象 class 对象主要有三个特性,继承.封装.多态.python的核心. 1.多态.封装.继承 多态,就算不知道变量所引用的类型,还是可以操作对象,根据类型 ...
- Python学习笔记16:标准库多线程(threading包裹)
Python主要是通过标准库threading包来实现多线程. 今天,互联网时代,所有的server您将收到大量请求. server要利用多线程的方式的优势来处理这些请求,为了改善网络port读写效率 ...
- Python学习笔记 - day7 - 类
类 面向对象最重要的概念就是类(Class)和实例(Instance),比如球类,而实例是根据类创建出来的一个个具体的“对象”,每个对象都拥有相同的方法,但各自的数据可能不同.在Python中,定义类 ...
- python学习笔记(七) 类和pygame实现打飞机游戏
python中类声明如下: class Student(object): def __init__(self, name, score): self.name = name self.score = ...
- Python学习笔记:类
类可以将数据与函数封装起来,用一个例子解释,先定义一个类: class athlete: def __init__(self,a_name,a_dob=None,a_times=[]): self.n ...
- python学习笔记1-元类__metaclass__
type 其实就是元类,type 是python 背后创建所有对象的元类 python 中的类的创建规则: 假设创建Foo 这个类 class Foo(Bar): def __init__(): ...
- Python学习笔记12—类
典型的类和调用方法: #!/usr/bin/env Python # coding=utf-8 __metaclass__ = type #新式类 class Person: #创建类 def __i ...
- Python 学习笔记 - 10.类(Class) 1
定义 Python 的 Class 比较特别,和我们习惯的静态语言类型定义有很大区别. 1. 使用一个名为 __init__ 的方法来完成初始化.2. 使用一个名为 __del__ 的方法来完成类似析 ...
- python学习笔记16(错误、异常)
一.什么是错误,什么是异常 错误是指在执行代码过程中发生的事件,它中断或干扰代码的正常流程并创建异常对象.当错误中断流程时,该程序将尝试寻找异常处理程序(一段告诉程序如何对错误做出响应的代码),以帮助 ...
随机推荐
- C# Lodop与C-Lopdop选择打印机
原文:https://www.cnblogs.com/huaxie/p/9766886.html https://www.cnblogs.com/huaxie/p/10857490.html http ...
- vue自定义指令获取焦点及过滤器修改时间
<template id="comp3"> <div id="app"> <model :list="selectedl ...
- 即时通讯(II)
Socket 连接Demo Socket客户端代码 #import "ViewController.h" //0.导入头文件 #include <netinet/in.h&g ...
- webpack webpack.config.js配置
安装指定版本的webpack npm install webpack@3.6 -g 安装live-server 运行项目插件 输入live-server 运行后自动打开网页 npm ins ...
- tenorflow 模型调优
# Create the Timeline object, and write it to a json from tensorflow.python.client import timeline t ...
- 树莓派 msmtp和mutt 的安装和配置
1,安装mutt sudo apt-get install mutt 2,安装msmtp sudo apt-get install msmtp 3,设置mutt /etc/Muttrc # 系统全局设 ...
- 在MySQL登录时出现Access denied for user 'root'@'localhost' (using password: YES) 拒绝访问,并可修改MySQL密码
这两天装了一个mysql 5.7数据库,但是在本地dos登陆不上去,报错Access denied for user 'root'@'localhost'(using password:YES): 也 ...
- CSS3选择器 ::selection选择器
“::selection”伪元素是用来匹配突出显示的文本(用鼠标选择文本时的文本).浏览器默认情况下,用鼠标选择网页文本是以“深蓝的背景,白色的字体”显示的,效果如下图所示: 从上图中可以看出,用鼠标 ...
- [HYSBZ - 3252] 攻略
问题描述 题目简述:树版[k取方格数] 众所周知,桂木桂马是攻略之神,开启攻略之神模式后,他可以同时攻略k部游戏.今天他得到了一款新游戏<XX 半岛>,这款游戏有n个场景(scene),某 ...
- VSCode必备插件
通用组件 1.汉化插件 https://marketplace.visualstudio.com/items?itemName=MS-CEINTL.vscode-language-pack-zh-ha ...