We have to define a class that will initiate a number, input a number and print the number in Python.
我们必须定义一个将初始化数字,输入数字并在Python中打印数字的类。
Here, we are defining a class named Number – which has a public variable named num, in the class, there are 3 methods:
在这里,我们定义了一个名为Number的类-它具有一个名为num的公共变量,该类中有3种方法:
__init__ :
__init__ :
To initialize the variable, it works as a construction in C++, java.
要初始化变量,它可以作为C ++,java中的构造。
inputNum() :
inputNum() :
This method will ask to the user to input the value.
该方法将要求用户输入值。
printNum() :
printNum() :
This method will print number (
此方法将打印数字(
num).
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
翻译自: https://www.includehelp.com/python/simple-program-of-a-class-input-and-print-a-number.aspx