
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create a Class to Accept and Print String in Python
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
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.
Advertisements