Home »
Python »
Python programs
Python | Simple program of a class (Input and print a number)
Here, we are writing a simple class program in Python that will input a number and print the number using class.
Submitted by IncludeHelp, on September 08, 2018
We have to define a class that will initiate a number, input a number and print the number in Python.
Here, we are defining a class named Number – which has a public variable named num, in the class, there are 3 methods:
- __init__ :
To initialize the variable, it works as a construction in C++, java.
- inputNum() :
This method will ask to the user to input the value.
- printNum() :
This method will print number (num).
Example:
# class definition
class Number:
# __init__ method just like a constructor
def __init__(self, num):
self.num = num;
# method to take input from user
def inputNum(self):
self.num = int(input("Enter an integer number: "))
# method to print the number
def printNum(self):
print "num:", self.num
# main code
# declare object of the class 'Number'
objN = Number(100);
objN.printNum()
# input from user
objN.inputNum()
objN.printNum()
Output
num: 100
Enter an integer number: 200
num: 200