Overview
This lecture explains how to create and use inner classes (a class inside another class) in Python, using a Student and Laptop example.
Classes and Object Basics
- A class can have variables and methods to represent data and actions.
- To create an object, use the class name with required parameters.
Defining the Student Class
- The Student class takes name and roll number as initialization parameters.
- Student objects store their name and roll number as attributes.
- A
show()
method prints a student's name and roll number.
Adding Related Details: Laptop Example
- Students also use laptops, which have their own properties like brand, CPU, and RAM.
- Rather than passing all laptop attributes individually, a Laptop class is created.
- The Laptop class is defined inside the Student class, making it an "inner class".
- The Student class creates a Laptop object during its initialization.
Using Inner Classes
- The inner Laptop class is only accessible through the outer Student class.
- To access laptop details, use
student_object.laptop.<attribute>
.
- Each Student object has its own distinct Laptop object (as shown by their different IDs).
- You can also instantiate the Laptop class from outside as
Student.Laptop()
.
Defining Methods in Inner Classes
- Both Student and Laptop classes can have their own
show()
methods to print details.
- To display all details, call the outer class's show method, which also calls the laptop's show method.
Key Terms & Definitions
- Inner Class — A class defined within another class; used when one class is only relevant within another.
- Object — An instance of a class containing data and methods as defined by the class.
- Method — A function defined inside a class, acting on objects of that class.
Action Items / Next Steps
- Practice creating inner classes in Python.
- Implement a similar structure for other related objects (e.g., Employee and Address).
- Review any provided sample code and experiment with object initialization and method calls.