📅  最后修改于: 2023-12-03 15:15:50.146000             🧑  作者: Mango
Inheritance_Training is a programming concept that allows a class to inherit properties and methods from another class, referred to as the parent or base class. This allows for code reuse and helps improve the organization and readability of code.
To implement Inheritance_Training in your code, you need to define a parent class and one or more child classes. The child classes will inherit properties and methods from the parent class.
# Define a parent class
class Vehicle:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def start_engine(self):
print("Starting engine")
# Define a child class that inherits from the parent class
class Car(Vehicle):
def __init__(self, make, model, year, num_doors):
# Call the constructor of the parent class to initialize the make, model, and year properties
super().__init__(make, model, year)
self.num_doors = num_doors
def unlock_doors(self):
print("Unlocking doors")
# Create an object of the Car class and call its methods
my_car = Car("Toyota", "Camry", 2022, 4)
my_car.start_engine()
my_car.unlock_doors()
In this example, we define a parent class Vehicle
that has a constructor and a start_engine
method. We then define a child class Car
that inherits from Vehicle
and has an additional property num_doors
and a method unlock_doors
. We create an object of Car
and call its methods. The start_engine
method is inherited from the parent class.