Python Program to Create a Class wherein a Method accepts a String from the User and Another Prints it

When it is required to create a class that has a method to accept a string from the user and another method to print the string, object-oriented programming is used. Here, a class is defined with attributes and methods that perform specific operations on user input.

Below is a demonstration for the same ?

Example

class StringHandler:
    def __init__(self):
        self.string = ""
    
    def get_data(self):
        self.string = input("Enter the string: ")
    
    def put_data(self):
        print("The string is:")
        print(self.string)

print("An object of the class is being created")
my_instance = StringHandler()
print("The 'get_data' method is being called")
my_instance.get_data()
print("The 'put_data' method is being called")
my_instance.put_data()

Output

An object of the class is being created
The 'get_data' method is being called
Enter the string: janewill
The 'put_data' method is being called
The string is:
janewill

How It Works

  • A class named StringHandler is defined with an __init__ method that initializes an empty string attribute.
  • The get_data() method accepts user input and stores it in the string attribute.
  • The put_data() method displays the stored string on the console.
  • An instance of the class is created and the methods are called to demonstrate the functionality.

Alternative Implementation

You can also create a more flexible version that accepts the string as a parameter ?

class StringHandler:
    def __init__(self):
        self.string = ""
    
    def set_string(self, text):
        self.string = text
    
    def get_string(self):
        return self.string
    
    def display_string(self):
        print(f"Stored string: {self.string}")

# Create instance and use methods
handler = StringHandler()
handler.set_string("Hello, World!")
handler.display_string()
print("Retrieved string:", handler.get_string())
Stored string: Hello, World!
Retrieved string: Hello, World!

Conclusion

This example demonstrates basic object-oriented programming in Python by creating a class that encapsulates string data and provides methods to input and output that data. The class approach provides better organization and reusability compared to using standalone functions.

Updated on: 2026-03-25T17:32:25+05:30

500 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements