python python中的简单类和继承

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python python中的简单类和继承相关的知识,希望对你有一定的参考价值。

class Car:
    """ 
    A Simple attempt to model a car.
    """
    def __init__(self, make, model, year):
        """Initilize car attributes."""
        self.make   = make
        self.model  = model
        self.year   = year

        # Fuel capacity and level in gallons
        self.fuel_capacity = 15
        self.fuel_level = 0

    def fill_tank(self):
        #fill gas tank to capacity.
        self.fuel_level = self.fuel_capacity
        print("Fuel tank is full.")

    def drive(self):
        print("The car is moving.")

    ## Update fuel level
    def update_fuel_level(self, new_level):
        if(new_level <= self.fuel_capacity):
            self.fuel_level = new_level
        else:
            print("The thank can't hold that much")

    ## Add Fuel Level
    def add_fuel(self, amount):
        if(self.fuel_level + amount <= self.fuel_capacity):
            self.fuel_level += amount
            print("Added fuel.")

        else:
            print("The tank won't hold that much.")


class ElectricCar(Car):
    """A simple model of an electric car"""

    def __init__(self, make, model, year):


        super().__init__(make, model, year)


        # attributes specific to electric cars.
        # Battery capacity in kWh.
        self.battery_size = 70
        # charge level in %
        self.charge_level = 0

    def charge(self):
        self.charge_level = 100
        print("The vehicle is fully charged.")


my_electric_car = ElectricCar('tesla', 'model s', 2016)
my_electric_car.charge()
my_electric_car.drive()

以上是关于python python中的简单类和继承的主要内容,如果未能解决你的问题,请参考以下文章

python 类和元类(metaclass)的理解和简单运用

Python类和对象

Python学习 Day14 python 类和元类(metaclass)的理解和简单运用

python3 语法学习 类和继承

python-多继承

python-多继承