2022年 11月 3日

Python | 类的简单程序(输入并打印数字)

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种方法:

  1. __init__ :

    __init__ :

    To initialize the variable, it works as a construction in C++, java.

    要初始化变量,它可以作为C ++,java中的构造。

  2. inputNum() :

    inputNum() :

    This method will ask to the user to input the value.

    该方法将要求用户输入值。

  3. printNum() :

    printNum() :

    This method will print number (

    此方法将打印数字(

    num).

    num )。

Example:

例:

  1. # class definition
  2. class Number:
  3. # __init__ method just like a constructor
  4. def __init__(self, num):
  5. self.num = num;
  6. # method to take input from user
  7. def inputNum(self):
  8. self.num = int(input("Enter an integer number: "))
  9. # method to print the number
  10. def printNum(self):
  11. print "num:", self.num
  12. # main code
  13. # declare object of the class 'Number'
  14. objN = Number(100);
  15. objN.printNum()
  16. # input from user
  17. objN.inputNum()
  18. objN.printNum()

Output

输出量

  1. num: 100
  2. Enter an integer number: 200
  3. num: 200

翻译自: https://www.includehelp.com/python/simple-program-of-a-class-input-and-print-a-number.aspx