9.4.5 导入模块中的所有类

要导入模块中的每个类,可使用下面的语法:

from mod import *

不推荐使用这种导入方式,其原因有二。首先,如果只要看一下文件开头的import语句,就能清楚地知道程序使用了哪些类,将大有裨益;但这种导入方式没有明确地指出你

使用了模块中的哪些类。这种导入方式还可能引发名称方面的困惑。如果你不小心导入了一个与程序文件中其他东西同名的类,将引发难以诊断的错误。这里之所以介绍这种导

入方式,是因为虽然不推荐使用这种方式,但你可能会在别人编写的代码中见到它




car.py代码如下:


"""A class that can be used to represent a car."""

class Car(object):

"""A simple attempt to represent a car."""

def __init__(self, manufacturer, model, year):

"""Initialize attributes to describe a car."""

self.manufacturer = manufacturer

self.model = model

self.year = year

self.odometer_reading = 0

def get_descriptive_name(self):

"""Return a neatly formatted descriptive name."""

long_name = str(self.year) + ' ' + self.manufacturer + ' ' + self.model

return long_name.title()

def read_odometer(self):

"""Print a statement showing the car's mileage."""

print("This car has " + str(self.odometer_reading) + " miles on it.")

def update_odometer(self, mileage):

"""

Set the odometer reading to the given value.

Reject the change if it attempts to roll the odometer back.

"""

if mileage >= self.odometer_reading:

self.odometer_reading = mileage

else:

print("You can't roll back an odometer!")

def increment_odometer(self, miles):

"""Add the given amount to the odometer reading."""

self.odometer_reading += miles

class Battery():

"""A simple attempt to model a battery for an electric car."""

def __init__(self, battery_size=60):

"""Initialize the batteery's attributes."""

self.battery_size = battery_size

def describe_battery(self):

"""Print a statement describing the battery size."""

print("This car has a " + str(self.battery_size) + "-kWh battery.")

def get_range(self):

"""Print a statement about the range this battery provides."""

if self.battery_size == 60:

range = 140

elif self.battery_size == 85:

range = 185

message = "This car can go approximately " + str(range)

message += " miles on a full charge."

print(message)

class ElectricCar(Car):

"""Models aspects of a car, specific to electric vehicles."""

def __init__(self, manufacturer, model, year):

"""

Initialize attributes of the parent class.

Then initialize attributes specific to an electric car.

"""

print "car ele\n"

super(ElectricCar,self).__init__(manufacturer, model, year)

self.battery = Battery()

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 以导入整个模块,再使用句点表示法访问需要的类。这种导入方法很简单,代码也易于阅读。由于创建类实例的代码都包含模块名...
    python大大阅读 378评论 0 0
  • 时间:12月18日 学员:刘芷语桐、李然云齐、王荣浩 任课教师:张老师 课程目标: 1.了解齿轮传动:加速运动:大...
    嘻_阅读 268评论 0 0
  • 不知道有谁会像我这样,在家一吃就不可收拾。溃于蚁穴,势如破竹,奔流到海不复还。吃的惯性太大,就算肚子撑圆了...
    露水糯阅读 301评论 0 0
  • 是一些动物,听说你们不喜欢铅笔稿,但我懒,就这样吧,正文如下 结束语:没有!
    风大啊阅读 155评论 0 2