Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
StringHandleris defined with an__init__method that initializes an empty string attribute. - The
get_data()method accepts user input and stores it in thestringattribute. - 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.
Advertisements
