#-*- coding:utf-8 -*- class Car(object): # 静态字段 通过Car.country来访问.(静态字段属于类)(普通字段属于对象) country = '中国' def __init__(self,make,model,year): # 普通字段 obj.name self.make = make self.model = model self.year = year self.odometer_reading =0 # self.name = '公有字段' # self.__foo = "私有字段" def display_descriptive_name(self): long_name = str(self.year)+ ' ' + self.make + ' ' + self.model print long_name.title() return long_name.title() def fill_gas_tank(self): return "This car need a gas tank!" def read_mileage(self): print 'This car has ' + str(self.odometer_reading) + ' miles on it' def update_odometer(self,mileage): if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print "You can't roll back an odometer" #经典类 # class ElectricCar(Car): # def __init__(self,make,model,year): # Car.__init__(self,make,model,year) #新式类 class ElectricCar(Car): def __init__(self,make,model,year,battery_model): self.battery_model = battery_model self.battery_size = 70 super(ElectricCar,self).__init__(make,model,year) #继承父类 def describe_battery(self): #增加一个子类的方法 print "This car has a " + str(self.battery_size) + " kwh battery" def fill_gas_tank(self): #类的方法重载,如果跟父类中有重名,子类会调用自己的同名方法 print 'This car does not need gas tank!' my_tesla = ElectricCar('tesla','M odel s','2017','松下NCR') my_tesla.display_descriptive_name() my_tesla.describe_battery() my_tesla.fill_gas_tank() # my_car = Car('audi','a8','2017') # my_car.display_descriptive_name() # # print my_car.fill_gas_tank() # my_car.update_odometer(100) # my_car.read_mileage()