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(错误、异常)
一.什么是错误,什么是异常 错误是指在执行代码过程中发生的事件,它中断或干扰代码的正常流程并创建异常对象.当错误中断流程时,该程序将尝试寻找异常处理程序(一段告诉程序如何对错误做出响应的代码),以帮助 ...
随机推荐
- Ftp客户端(上传文件)
#coding=utf-8 import os import socket import hashlib import json # client = socket.socket() #申明socke ...
- C++11常用特性总结
非原创,转载出处 http://www.cnblogs.com/feng-sc C++11已经出来很久了,网上也早有很多优秀的C++11新特性的总结文章,在编写本博客之前,博主在工作和学习中学到的关于 ...
- Latex--入门系列二
Latex 专业的参考 tex对于论文写作或者其他的一些需要拍版的写作来说,还是非常有意义的.我在网上看到这个对于Latex的入门介绍还是比较全面的,Arbitrary reference.所以将会翻 ...
- js中的函数声明置顶
函数声明置顶是指 js引擎在读取变量与声明式函数时,会优先读取,例如如下 var a = 1: function a(){}; console.log(a); //这里得到的为1,而不是该functi ...
- srs-librtmp pusher(push h264 raw)
Simple Live System Using SRS https://www.cnblogs.com/dong1/p/5100792.html 1.上面是推送文件,改成推送缓存 封装了三个函数 i ...
- 安装Git,Maven,配置ssh认证
安装git: yum -y install git 安装maven: wget http://mirror.bit.edu.cn/apache/maven/maven-3/3.6.1/binaries ...
- JS基础入门篇(七)—运算符
1.算术运算符 1.算术运算符 算术运算符:+ ,- ,* ,/ ,%(取余) ,++ ,-- . 重点:++和--前置和后置的区别. 1.1 前置 ++ 和 后置 ++ 前置++:先自增值,再使用值 ...
- gulp自动化构建工具使用总结
简介: gulp是前端开发过程中对代码进行构建的工具,是自动化项目的构建利器:她不仅能对网站资源进行优化,而且在开发过程中很多重复的任务能够使用正确的工具自动完成:使用她,我们不仅可以很愉快的编写代码 ...
- 关于python读写文件的r+方式的坑
写脚本的时候需要将文件中的一行修改,我的修改逻辑是,用r+方式打开文件,然后将原文件数据读入一个数组,修改数组的对应元素,在seek(0),然后将数组write进文件 结果: 文件文件末尾总是多出一行 ...
- Python---基础---爱因斯坦阶梯问题
写一个程序,打印出0-100所有奇数 ls = range(0, 101)for i in ls: if i % 2 == 1: print(i)--------------------------- ...