我们在编码的过程中,可能会给对象添加越来越多的功能,即使我们使用了继承,也不可避免的使文件越来越臃肿。

为了避免这种情况, 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 类 - 导入的更多相关文章

  1. python学习笔记4_类和更抽象

    python学习笔记4_类和更抽象 一.对象 class 对象主要有三个特性,继承.封装.多态.python的核心. 1.多态.封装.继承 多态,就算不知道变量所引用的类型,还是可以操作对象,根据类型 ...

  2. Python学习笔记16:标准库多线程(threading包裹)

    Python主要是通过标准库threading包来实现多线程. 今天,互联网时代,所有的server您将收到大量请求. server要利用多线程的方式的优势来处理这些请求,为了改善网络port读写效率 ...

  3. Python学习笔记 - day7 - 类

    类 面向对象最重要的概念就是类(Class)和实例(Instance),比如球类,而实例是根据类创建出来的一个个具体的“对象”,每个对象都拥有相同的方法,但各自的数据可能不同.在Python中,定义类 ...

  4. python学习笔记(七) 类和pygame实现打飞机游戏

    python中类声明如下: class Student(object): def __init__(self, name, score): self.name = name self.score = ...

  5. Python学习笔记:类

    类可以将数据与函数封装起来,用一个例子解释,先定义一个类: class athlete: def __init__(self,a_name,a_dob=None,a_times=[]): self.n ...

  6. python学习笔记1-元类__metaclass__

    type 其实就是元类,type 是python 背后创建所有对象的元类   python 中的类的创建规则: 假设创建Foo 这个类 class Foo(Bar): def __init__(): ...

  7. Python学习笔记12—类

    典型的类和调用方法: #!/usr/bin/env Python # coding=utf-8 __metaclass__ = type #新式类 class Person: #创建类 def __i ...

  8. Python 学习笔记 - 10.类(Class) 1

    定义 Python 的 Class 比较特别,和我们习惯的静态语言类型定义有很大区别. 1. 使用一个名为 __init__ 的方法来完成初始化.2. 使用一个名为 __del__ 的方法来完成类似析 ...

  9. python学习笔记16(错误、异常)

    一.什么是错误,什么是异常 错误是指在执行代码过程中发生的事件,它中断或干扰代码的正常流程并创建异常对象.当错误中断流程时,该程序将尝试寻找异常处理程序(一段告诉程序如何对错误做出响应的代码),以帮助 ...

随机推荐

  1. wxpython模板程序,包括各个实例

    #coding=utf-8 import wx import time import os class MyApp(wx.App): def __init__(self): wx.App.__init ...

  2. 01-HTML控件

    1.HTML (常用标签 网页的基本结构)2.CSS (常用样式 网页的显示效果)3.JavaScript (用户交互效果 动态效果)4.jQuery (JavaScript库 简化原生js操作)5. ...

  3. Add JWT Bearer Authorization to Swagger and ASP.NET Core

    Add JWT Bearer Authorization to Swagger and ASP.NET Core     If you have an ASP.NET Core web applica ...

  4. more - 在显示器上阅读文件的过滤器

    总览 (SYNOPSIS) more [-dlfpcsu ] [-num ] [+/ pattern] [+ linenum] [file ... ] 描述 (DESCRIPTION) More 是 ...

  5. python基础--3 列表

    #list类#li是list类的一个对象li=[11,22,33,22,44] #参数#在原来值最后进行整个作为元素追加 # li.append((11,22,33))#对列表本身进行操作,appen ...

  6. Mybatis学习笔记大纲

    Mybatis学习笔记大纲: 一.MyBatis简介 二.MyBatis-HelloWorld 三.MyBatis-全局配置文件 四.MyBatis-映射文件 五.MyBatis-动态SQL 六.My ...

  7. jmeter中遇见的坑:url需要编码的

    在postman中能请求成功,但是在jmeter就是请求失败报500错. 请求的 url  :/graph/vertices?label=node&properties={"num& ...

  8. win7系统安装sql2000数据库时没有反应,不出来安装界面?

    今天一个客户反馈软件连不上数据库,经检查发现SQL服务启动不了,懒得查原因就把SQL2000卸载了,他们电脑是win7的系统,本来正常来说安装SQL2000数据库是没啥问题的,可是特别奇怪的是,这台w ...

  9. PHPExcel 之常用功能

    PHPExcel基本操作: 定义EXCEL实体 即定义一个PHPEXCEL对象,并设置EXCEL对象内显示内容 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ...

  10. Power Strings POJ - 2406

    Power Strings POJ - 2406 时限: 3000MS   内存: 65536KB   64位IO格式: %I64d & %I64u 提交 状态 已开启划词翻译 问题描述 Gi ...