关于Python的类,首先定义一个Car类:?
#定义一个Car类
class Car:
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive(self):
long_name = f"{self.year} {self.make} {self.model}"
return long_name.title()
def read_odometer(self):
print(f"This car has {self.odometer_reading} miles on it.")
def update_odemeter(self,mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odermeter(self,miles):
self.odometer_reading += miles
然后以Car类为父类,定义一个子类ElectricCar,并使用super().__init__(),继承父类,并能够调用父类Car的方法,并添加属性battery:
定义一个Car的子类:ElectricCar类
class ElectricCar(Car):
#初始化父类Car的属性
def __init__(self,make,model,year):
super().__init__(make,model,year)
self.battery_size = 75
self.battery = Battery()
在实现子类和父类之后,可在定义一个类,将其作为ElectricCar类的一个属性,实现将实例用作属性:
#定义一个Battery类作为实例,将其作为属性
class Battery():
def __init__(self,battery_size=75):
self.battery_size = battery_size
def describe_battery(self):
print(f"This car has a {self.battery_size} kwh battery.")
调用:
创建一个实例,并通过ElectricCar类调用Battery,打印出电动汽车的电瓶里程:
mycar = ElectricCar('tesla','model S',2019)
print(mycar.get_descriptive())
mycar.battery.battery_size=80
mycar.battery.describe_battery()
运行结果如下:
?
|