Python-函数,,class Vehi


class Vehicle:
#Vehicle类被称为基本类或超类,Car类和Bike类被成为导出类或子类。
def __init__(self, speed):
# __init__函数会在类被创建的时候自动调用,用来初始化类。它的参数,
# 要在创建类的时候提供。于是我们通过提供一个数值来初始化speed的值。
# __init__是python的内置方法
self.speed = speed
def drive(self, distance):
print ‘need %f hour(s)‘ % (distance / self.speed)


class Bike(Vehicle):
#class定义后面的括号里表示这个类继承于哪个类。Bike(Vehicle)就是说Bike
#是继承自Vehicle中的子类。
# Vehicle中的属性和方法,Bike都会有。
pass


class Car(Vehicle):
def __init__(self, speed, fuel):
#重新定义了__init__和drive函数,这样会覆盖掉它继承自Vehicle的同名函数。
#但我们依然可以通过“Vehicle.函数名”来调用它的超类方法。以此来获得它作
#为Vehicle所具有的功能。
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)

Python-函数

评论关闭