码迷,mamicode.com
首页 > 编程语言 > 详细

Python #面向对象

时间:2017-09-23 20:23:37      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:方法重载   python   调用   面向   coding   中国   访问   pytho   long   

 

#-*- 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()

 

Python #面向对象

标签:方法重载   python   调用   面向   coding   中国   访问   pytho   long   

原文地址:http://www.cnblogs.com/lwsup/p/7582022.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!