导入类或模块
利用上篇文章中car类来进行导入
导入类时需要使用from..import..关键字/亦或者导入整个模块import...
导入car类,虽然已经存在car.py的文件,但这个模块也应该命名为car.py,因为它表示包含car的代码
将Car类存储在一个名为car.py的模块中,该模块将覆盖前面使用的文件名car.py
首先需要创建Car.py的模块,其中只包含Car类的代码,如下:
'''表示汽车的类''' class car(): def __init__(self,make,model,year): self.make=make self.model=model self.year=year self.odomember=0 def get_descriptive_name(self): long_name=str(self.year)+' '+self.make+' '+self.model return long_name.title() def read_odomember(self): print("This car has"+str(self.odomember)+"miles on it.") def update_odomember(self,mileage): if mileage>=self.odomember: self.odomember=mileage else: print("Yor Can't roll back an odomember!") def increment_odomeber(self,miles): self.odomember+=miles my_user_car=car('China','奥迪',2016) print(my_user_car.get_descriptive_name()) my_user_car.read_odomember() my_user_car.odomember=12 my_user_car.read_odomember() my_user_car.update_odomember(260) my_user_car.read_odomember() my_user_car.increment_odomeber(16000) my_user_car.read_odomember() """继承""" class battery(): def __init__(self,battery_size=70): self.battery_size=battery_size def describe_battery(self): print("The ElectricCar has a "+str(self.battery_size) + "-KWH battery") def get_range(self): if self.battery_size==70: range=240 elif self.battery_size==80: range=320 messgae="This car can go approximately"+str(range) messgae+="mules on a full charge" print(messgae) class ElectricCar(car): def __init__(self,make,model,year): super().__init__(make,model,year) self.battery=battery() my_tesla=ElectricCar('tesla','model s',2016) print(my_tesla.get_descriptive_name()) my_tesla.battery.describe_battery() my_tesla.battery.get_range()
下面进行创建另一个文件,my_car.py,在其中导入Car类并创建实例
from car import Car my_new_car=Car('china','BYD',2018) print(my_new_car.get_desciptive_name()) my_new_car.odometer=23