In this tutorial, we will learn how to return an instance of a class in Python. Returning an instance of a class is a common practice in object-oriented programming (OOP) to create and manipulate objects. This tutorial will guide you through creating a simple class and how to return its instances using methods.
Step 1: Create a Class
First, let’s create a simple class called Student
with an __init__()
method that initializes the attributes name
and age
.
1 2 3 4 |
class Student: def __init__(self, name, age): self.name = name self.age = age |
Step 2: Create a Method to Return an Instance of the Class
Now, let’s create a method called create_student()
inside the class that takes the name and age as arguments and returns an instance of the Student
class with these attributes.
1 2 3 4 5 6 7 8 |
class Student: def __init__(self, name, age): self.name = name self.age = age @classmethod def create_student(cls, name, age): return cls(name, age) |
Notice the @classmethod
decorator above the create_student()
method. This decorator lets us define a method as a class method. A class method takes a reference to the class itself as its first argument, typically named cls
. Since a class method only has access to the class itself, it can be used to create and return a new instance of the class.
Step 3: Creating and Manipulating Instances of the Class
Now that we have our class with the create_student()
method, we can create instances of the Student
class and manipulate their attributes. For example, let’s create an instance of the Student
class and display its name and age attributes.
1 2 3 4 5 |
# Create a new Student instance new_student = Student.create_student("John Doe", 20) # Print the new student's name and age print(f"Name: {new_student.name}, Age: {new_student.age}") |
Output:
Name: John Doe, Age: 20
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class Student: def __init__(self, name, age): self.name = name self.age = age @classmethod def create_student(cls, name, age): return cls(name, age) # Create a new Student instance new_student = Student.create_student("John Doe", 20) # Print the new student's name and age print(f"Name: {new_student.name}, Age: {new_student.age}") |
Conclusion
In this tutorial, we learned how to return an instance of a class in Python using a class method. This is a useful technique in OOP for creating and manipulating objects. Now, you can implement this technique in your Python projects to utilize the power of OOP.