class Vehicle:
def __init__(self, speed = 60.0):
self.speed = speed
#下一个函数需要这个值
def drive(self, distance):
print("need %f hour" % (distance / self.speed))
class Bike(Vehicle):
pass
class Car(Vehicle):
def __init__(self, speed, fuel):
Vehicle.__init__(self, speed)
self.fuel = fuel
def drive(self, distance):
Vehicle.drive(self, distance)
print("need %f fuels" % (distance * self.fuel))
b = Bike(15.0)
c = Car(80.0, 0.012)
b.drive(100.0)
c.drive(100.0)
以上程序中所用到的知识点如下:
#类创建的时候自动调用,用来初始化类
#类方法的第一个参数必须为self #调用类方法时,不需要额外提供self这个参数的值 #self在类方法中的值,就是你调用的对象本身
用法
def 函数名(name = 默认值):
函数体
#当没有提供参数,函数使用默认值 #若提供参数,优先使用提供的 #函数有多个参数时,默认参数必须在末尾
用法:子类名(父类名) #父类中有的属性和方法,子类都会有 #不需要额外功能的子类,用pass在类中保留空块
#空语句,什么也不做 #用来保证格式的完整性
#子类同名函数会对父类覆盖
用法:父类名.函数名() #获得该方法作为父类所具有的功能 #方法必须提供self的参数
用法:mc = MyClass()