Python Foundation - 9.3 Inheritance

· When a class inherits another class, it automatically acquires all the attributes and methods of another class; the original class is the parent class, and the new class is called the subclass. Subclasses inherit all attributes and methods of their parent classes, and can also define their own attributes and methods.

 

Method of 9.3.1 subclass _inint_()

Create an electric_car inheritance from the previous Car class

class ElectricCar(Car):  # To define a subclass, you need to specify the parent class name in parentheses
    """The Uniqueness of Electric Vehicle"""

    def __init__(self,make, model, year):
        """Initialize parent class properties"""
        super().__init__(make, model, year)  # Call the method _init_ of the parent class so that ElectricCar contains all the attributes of the parent class


my_electric_car = ElectricCar('bmw', 'mosel s', 2016)
my_electric_car.get_descriptive_name()

 

Inheritance in 9.3.2 Python 2.7

1. The function super() requires two arguments: the subclass name and the object self.

2. Specify the object in parentheses when defining the parent class.

class Car(object):
    def __init__(self,make, model, year):
        --snip--
        
class ElectricCar(Car):
    def __init__(self, make, model, year):
        super(ElectricCar, self).__init__(make, model, year)
        --snip--

 

9.3.3 Define attributes and methods for subclasses

class ElectricCar(Car):  # To define a subclass, you need to specify the parent class name in parentheses
    """The Uniqueness of Electric Vehicle"""

    def __init__(self,make, model, year):
        """
        //Initialize parent class properties
        //Reinitialization of the unique properties of electric vehicles
        """
        super().__init__(make, model, year)  # Call the method _init_ of the parent class to make ElectricCar contain all Frey's attributes
        self.battery_size = 70

    def describe_battery(self):
        """Print a message describing battery capacity"""
        print("This car has a " + str(self.battery_size) + "-kwh battery")


my_electric_car = ElectricCar('bmw', 'mosel s', 2016)
my_electric_car.get_descriptive_name()
my_electric_car.describe_battery()

9.3.4 Method of overwriting parent class

Define a method in a subclass that is renamed with the parent class that needs to be overridden, so that Python ignores the method in the parent class and uses the method in the subclass.

9.3.5 Use instances as attributes

Add Battery() class and related methods

class Car():
    """A Simple Attempt to Simulate a Vehicle"""

    def __init__(self, make, model, year):  # Note that the _inint_ underscore is two on each side, and if there is an error, the take no arguments error will be reported.
        """Initialization Describes the Properties of a Vehicle"""
        self.make = make
        self.model = model
        self.year = year
        # Add odometer_reading attribute to make its initial value 0
        self.odometer_reading = 20

    def get_descriptive_name(self):
        """Return neat description information"""
        long_name = str(self.year) + " " + self.make + ' ' + self.model
        print(long_name.title())

    def update_odometer(self, mileage):
        """Set the odometer reading to the specified value"""
        # self.odometer_reading = mileage
        """                                                                                          
        //Set the odometer reading to the specified value                                                                                
        //No callback of odometer readings                                                                                  
        """
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer !")

    def increment_odometer(self, miles):
        """
        //Increase the odometer reading by a specified amount
        //Prohibited increments are negative
        """
        if miles >= 0:
            self.odometer_reading += miles
        else:
            print("You can't add negative number on  odometer !")

    def read_odometer(self):
        """Print a message indicating the mileage of the car"""
        print("This car has " + str(self.odometer_reading) + " miles on it.")


class Battery():
    """A Simple Attempt to Simulate Electric Vehicle Battery"""
    def __init__(self, battery_size=70):
        """"Initialize Battery Properties"""
        self.battery_size = battery_size

    def describe_battery(self):
        """Print a message describing battery capacity"""
        print("This car has a " + str(self.battery_size) + "-kwh battery")

    def get_range(self):
        """Print a message indicating the mileage of the battery car"""
        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)


class ElectricCar(Car):  # To define a subclass, you need to specify the parent class name in parentheses
    """The Uniqueness of Electric Vehicle"""

    def __init__(self, make, model, year):
        """
        //Initialize parent class properties
        //Reinitialization of the unique properties of electric vehicles
        """
        super().__init__(make, model, year)  # Call the method _init_ of the parent class to make ElectricCar contain all Frey's attributes
        self.battery = Battery()


my_electric_car = ElectricCar('bmw', 'model s', 2016)
my_electric_car.get_descriptive_name()
my_electric_car.battery.describe_battery()
my_electric_car.battery.get_range()

 

Practice:

9-6

# 9-6 Ice Cream Shop
class Restaurant():
    def __init__(self, restaurant_name, cuisine_type):
        self.name = restaurant_name
        self.type = cuisine_type

    def describe_restaurant(self):
        print("\nThe restaurant's name is " + self.name.title() + "!")
        print("\nThe restaurant is " + self.type + "!")

    def open_restsurant(self):
        print("\n" + self.name.title() + " is open !")


class IceCreamStand(Restaurant):
    def __init__(self, restaurant_name='gg', cuisine_type='dd'):
        # flavors = []
        super().__init__(restaurant_name, cuisine_type)
        self.flavors = ['Blueberry', 'Strawberry', 'Mango']
        print(self.flavors)


restaurant1 = IceCreamStand()

 

 

 

Tags: Python Attribute

Posted on Sat, 05 Oct 2019 23:35:33 -0700 by Niruth