zoukankan      html  css  js  c++  java
  • python基础知识(继承)

    继承的基本语法

    class  Class(继承那个基类如果有多个基类用逗号隔开,如果没有就继承object):

      """ 类的帮助信息"""

      类体

    方法重写

    派生类中调用基类的__init__()方法

    方法重写

    在派生类中重写方法

    在派生类中调用基类的__init__()方法

    super()可以在派生类当中调用基类的构造方法

    class Car():
      """一次模拟汽车的简单尝试"""
      def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0
        
      def get_descriptive_name(self):
        long_name = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name.title()
     
      def read_odometer(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!")
          
      def increment_odometer(self, miles):
        self.odometer_reading += miles

    class Battery():

      def __init__(self, battery_size = 70):
        self.battery_size = battery_size

      def print_battery(self):
        print(self.battery_size)

      def get_range(self):
        """打印一条消息,指出电瓶的续航里程"""
        if self.battery_size == 70:
          range = 240
        elif self.battery_size == 85:
          range = 270
        message = "This car can go approximately " + str(range)
        message += " miles on a full charge."
        print(message)

      def upgrade_battery(self):
        if self.battery_size != 85:
          self.battery_size = 85
        print(self.battery_size)

    class ElectricCar(Car):
          #电动汽车的独特之处
        def __init__(self, make, model, year):
          #初始化父类的属性
          super().__init__(make, model, year)
          self.battery =Battery()
              
    my_tesla = ElectricCar('tesla', 'model s', 2016)
    print(my_tesla.get_descriptive_name())
    my_tesla.battery.upgrade_battery()
    my_tesla.battery.print_battery()
    my = ElectricCar('tesla', 'model s', 2017)
    my.battery.get_range()
    my.battery.upgrade_battery()
    my.battery.get_range()


  • 相关阅读:
    Jmeter+ant+jenkin接口自动化发邮件
    BadBoy 参数化录制,并导入JMeter
    Jmeter 移动端录制
    Pytest 操作
    Pytest框架简介与安装
    Fiddler iOS抓包
    Fiddler Android APP 抓包
    random的使用
    scanner的使用与匿名对象的使用
    标准的类,API的初步使用
  • 原文地址:https://www.cnblogs.com/zhangjiantaocs/p/11969750.html
Copyright © 2011-2022 走看看