Class Definition
Class Vehicle:
class Vehicle:
def __init__(self, color):
self.color = color
Class Declaration: class Vehicle: defines a class named Vehicle.
Constructor: def __init__(self, color): defines the constructor method (__init__). It initializes a new instance of Vehicle.
Instance Variable: self.color = color assigns the value of the parameter color to the instance variable self.color.
Class Car (Inheritance):
class Car(Vehicle):
def __init__(self, color, model):
super().__init__(color)
self.model = model
Class Declaration with Inheritance: class Car(Vehicle): defines a class named Car that inherits from the Vehicle class.
Constructor: def __init__(self, color, model): defines the constructor method (__init__). It initializes a new instance of Car.
Calling Superclass Constructor: super().__init__(color) calls the constructor of the superclass Vehicle to initialize the color attribute.
Instance Variable: self.model = model assigns the value of the parameter model to the instance variable self.model.
Object Instantiation
Creating an Instance:
my_car = Car("Red", "Toyota")
This line creates an instance of the Car class with color set to "Red" and model set to "Toyota". The constructor of the Vehicle class is also called to initialize the color attribute.
Accessing Attributes
Printing the Model:
print(my_car.model)
This line prints the model attribute of the my_car object, which is "Toyota".
Complete Code
Here is the complete code for clarity:
class Vehicle:
def __init__(self, color):
self.color = color
class Car(Vehicle):
def __init__(self, color, model):
super().__init__(color)
self.model = model
my_car = Car("Red", "Toyota")
print(my_car.model)
Output
The output of the code is: Toyota
Explanation Summary
Vehicle Class: Defines a vehicle with a color.
Car Class: Inherits from Vehicle and adds a model attribute.
Object Creation: An instance of Car is created with color "Red" and model "Toyota".
Attribute Access: The model attribute of my_car is printed, displaying "Toyota".
0 Comments:
Post a Comment