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 that accepts a string from the user, and another method that prints the string, object oriented method is used. Here, a class is defined, and attributes are defined. Functions are defined within the class that perform certain operations. An instance of the class is created, and the functions are used to perform calculator operations.

Below is a demonstration for the same −

Example

 Live Demo

class print_it():
   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 = print_it()
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

Explanation

  • A class named ‘print_it’ class is defined, that has functions like ‘get_data’, and ‘put_data’.
  • These are used to perform operations such as get data from user and display it on screen respectively.
  • An instance of this class is created.
  • The value for the string is entered, and operations are performed on it.
  • Relevant messages and output is displayed on the console.

Updated on: 12-Mar-2021

274 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements