Code Explanation:
1. Class Engine definition
class Engine:
Explanation
Declares a class named Engine.
A class is a blueprint for creating objects (here: engine objects).
2. start method inside Engine
def start(self):
return "Start"
Explanation
Defines an instance method start that takes self (the instance) as its only parameter.
When called on an Engine object it returns the string "Start".
Nothing else (no print) — it just returns the value.
3. Class Car definition
class Car:
Explanation
Declares a class named Car.
This class will represent a car and, as we’ll see, it will contain an Engine object (composition / “has-a” relationship).
4. __init__ constructor of Car
def __init__(self):
self.e = Engine()
Explanation
__init__ is the constructor — it runs when a Car object is created.
self.e = Engine() creates a new Engine instance and assigns it to the instance attribute e.
So every Car object gets its own Engine object accessible as car_instance.e.
5. Creating a Car object
c = Car()
Explanation
Instantiates a Car object and stores it in variable c.
During creation, Car.__init__ runs and c.e becomes an Engine instance.
6. Calling the engine start method and printing result
print(c.e.start())
Explanation
c.e accesses the Engine instance stored in the Car object c.
c.e.start() calls the start method on that Engine instance; it returns the string "Start".
print(...) prints the returned string to the console.
Final Output
Start


0 Comments:
Post a Comment