如何使用 Python 类并要求用户输入?

MrN*_*9uy 0 python class

这是我第一次尝试创建和使用类。当我要求用户输入时发生错误。我收到以下错误:

n1 = Arithmetic.float_input("Enter your First number: ")
TypeError: float_input() missing 1 required positional argument: 'msg'
Run Code Online (Sandbox Code Playgroud)

这是我的代码。

# Define class
class Arithmetic:
    def float_input(self, msg): # Use this function for exception handling during user input
        while True:
            try:
                return float(input(msg))
            except ValueError:
                print("You must enter a number!")
            else:
            break
    def add(self, n1, n2):
        sum1 = n1 + n2
        print(n1,"+" ,n2,"=", sum1)
    def sub(self, n1, n2):
        diff = n1 - n2
        print(n1,"-",n2,"-", diff)
    def mult(self, n1, n2):
        product = n1 * n2
        print(n1,"*",n2, "=", product)
    def div(self, n1, n2):
        if n2 == 0:
            print(n1, "/",n2,"= You cannot divide by Zero")
        else:
            quotient = n1 / n2
            print(n1, "/",n2,"=", quotient)
    def allInOne(self, n1, n2):
        #Store values in dictionary (not required, just excercising dictionary skill)
        res = {"add": add(n1, n2), "sub": sub(n1, n2), "mult": mult(n1, n2), "div": div(n1, n2)}

# Declare variables. Ask user for input and use the exception handling function       
n1 = Arithmetic.float_input("Enter your First number: ")
n2 = Arithmetic.float_input("Enter your Second number: ")
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

AKX*_*AKX 5

如果您有 Java 背景,那么值得知道的是,除非您需要由self.

无论如何,您看到的错误是因为您的方法未标记@classmethod@staticmethod因此需要类的实例,而您只是通过类本身调用它们(因此没有隐式实例或类对象作为第一个传入范围)。

因此,您的选择是:

1 – 创建一个实例Arithmetic()并使用它:

arith = Arithmetic()
n1 = arith.float_input("Enter your First number: ")
n2 = arith.float_input("Enter your Second number: ")
Run Code Online (Sandbox Code Playgroud)

2 – 将方法标记为静态,例如

@staticmethod
def float_input(prompt):  # note: no `self`
Run Code Online (Sandbox Code Playgroud)

3 – 标记方法类方法,例如

@classmethod
def float_input(cls, prompt):  # `cls` is `Arithmetic` (or its subclass) itself
Run Code Online (Sandbox Code Playgroud)

4 – 使方法只是没有类的常规函数​​。