zoukankan      html  css  js  c++  java
  • Python #面向对象

    #-*- 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()
  • 相关阅读:
    jQuery自定义选项卡插件
    jQuery委托事件delegate()方法
    发布/订阅模式
    Node.js + Nginx WNMP 多域名 多端口 反向代理
    让Nginx支持apk、ipa文件下载
    jQuery中bind方法传参
    Http协议详解
    vuecli2.X环境搭建
    vue绑定属性、绑定class及绑定style
    vue数据渲染、条件判断及列表循环
  • 原文地址:https://www.cnblogs.com/lwsup/p/7582022.html
Copyright © 2011-2022 走看看