加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
9.3.4将实例作为属性.py 2.38 KB
一键复制 编辑 原始数据 按行查看 历史
旺仔牛奶 提交于 2022-11-09 13:21 . update README.md.
class Car:
'''A simple attempt to simulate a car'''
def __init__(self,make,model,year):
'''Initialize the attributes that describe the car'''
self.make=make
self.model=model
self.year=year
self.odometer_reading=0
def get_descriptive_name(self):
'''Return neat descriptive informaiton'''
long_name=f"{self.year} {self.make} {self.model}"
return long_name.title()
def read_odometer(self):
'''Print a message indicating car mileage'''
print(f"This car has {self.odometer_reading} miles on it .")
#使用方法修改属性
def update_odometer(self,mileage):
'''
Set the odometer reading to the specified value
Do not reverse the odometer reading
'''
if mileage>=self.odometer_reading:
self.odometer_reading=mileage
else:#此处是禁止将里程表读数往回调
print("You can't roll back an odometer !")
#通过方法对属性的值进行递增
def increment_odometer(self,miles):
'''Increase the odometer reading by a specified amount
Suppress negative increments
'''
if miles>=0:
self.odometer_reading+=miles
else:
print("Error increase !")
class Battery:
'''A simple attempt to simulate electric vehicle battery'''
def __init__(self,battery_size=75):
self.battery_size=battery_size
def describe_battery(self):
'''Print a message describing the battery capcity'''
print(f"This car has a {self.battery_size}-kwh battery")
def get_range(self):
'''Print a message indicating the battery range'''
if self.battery_size==75:
range=20
elif self.battery_size==100:
range=315
class ElectricCar(Car):
'''The uniqueness of the electric car'''
def __init__(self,make,model,year):
'''
Initialize the properties of the parent class
Reinitialize unique attributes of electric vehicles
'''
super().__init__(make,model,year)
self.battery=Battery()
print(f"This car can go about {range} miles on a full charge")
my_tesla=ElectricCar('tesla','model s',2019)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化