9.4 导入类

2017-09-24  本文已影响0人  python大大

随着你不断地给类添加功能,文件可能变得很长,即便你妥善地使用了继承亦如此。为遵循Python的总体理念,应让文件尽可能整洁。为在这方面提供帮助,Python允许你将类存

储在模块中,然后在主程序中导入所需的模块。

9.4.1导入单个类

下面来创建一个只包含Car类的模块。这让我们面临一个微妙的命名问题:在本章中,已经有一个名为car.py的文件,但这个模块也应命名为car.py,因为它包含表示汽车的代

码。我们将这样解决这个命名问题:将Car类存储在一个名为car.py的模块中,该模块将覆盖前面使用的文件car.py。从现在开始,使用该模块的程序都必须使用更具体的文件

名,如my_car.py。下面是模块car.py,其中只包含Car类的代码

进入

https://www.tutorialspoint.com/online_python_ide.php

点右键,"create files",如图:

重命名新创建文件,如图。

程序如下:

car.py

main.py

car.py的程序:

#!/usr/bin/python

# -- coding: utf-8 --

"""一个可用于表示汽车的类"""

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):

"""

将里程表读数设置为指定的值

拒绝将里程表往回拨

"""

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

main.py的源码:

#!/usr/bin/python

# -- coding: utf-8 --

from car import Car

tc =Car("tsl","100S",2015)

print(tc.get_descriptive_name())

上一篇 下一篇

猜你喜欢

热点阅读