Connecting two classes in Python is a basic yet powerful concept. This tutorial will take you through the steps of connecting two classes, using a student and course as simple examples, to illustrate this concept. With classes, you can achieve complex functionality by reusing code in an organized and efficient way.
Step 1: Define the First Class
In Python, we define a class using the class keyword, followed by the name of the class. Here, we will define a class named ‘Student’ with a method to initialize the student’s name.
1 2 3 |
class Student: def __init__(self, name): self.name = name |
Step 2: Define the Second Class
Next, we’ll define our ‘Course’ class. This will include a method that accepts a Student object. We can use the Student object to access the student’s name.
1 2 3 4 5 6 |
class Course: def __init__(self): self.students = [] def add_student(self, student): self.students.append(student.name) |
Step 3: Instantiating the Classes
We’ll create an instance of our classes and connect them. We’ll first create a Student object, then we’ll create a Course object and add the student to the course.
1 2 3 4 5 6 7 |
# Creating student objects student1 = Student("John Doe") # Creating course objects course1 = Course() course1.add_student(student1) |
After this, John Doe will be added to the students list in course1.
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class Student: def __init__(self, name): self.name = name class Course: def __init__(self): self.students = [] def add_student(self, student): self.students.append(student.name) # Creating student objects student1 = Student("John Doe") # Creating course objects course1 = Course() course1.add_student(student1) print(course1.students) |
['John Doe']
Conclusion
By wrapping up, we can see that Python classes can easily be connected and used together for various purposes. As you get more comfortable with this concept, you’ll find that it’s a powerful way to structure your code for reusability and simplicity. Happy coding!