Py学习  »  Python

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

MrN1ce9uy • 5 年前 • 1393 次点击  

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

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

这是我的密码。

# 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: ")

我错过了什么?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/51665
 
1393 次点击  
文章 [ 4 ]  |  最新文章 5 年前
a_m_dev
Reply   •   1 楼
a_m_dev    5 年前

最好先实例化类,然后使用它的适当方法,如下所示

n1 = new Arithmetic()

n1.float_input('Enter your First number: ')
Yunbo Sim
Reply   •   2 楼
Yunbo Sim    5 年前

固定为:

# Declare variables. Ask user for input and use the exception handling function       
arithmatic = Arithmetic()
n1 = arithmatic.float_input("Enter your First number: ")
n2 = arithmatic.float_input("Enter your Second number: ")
JeanExtreme002
Reply   •   3 楼
JeanExtreme002    5 年前

问题是您没有创建 Arithmetic 在调用方法之前。因为您没有创建对象,所以不会向 self 参数。这会导致消息 "Enter your first number:" 传递给 自己 参数和 msg 参数为空。

要解决此问题,只需在类名后面使用括号创建一个对象,例如:

# 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: ")

如果不是故意创建对象,则可以使用 @classmethod 类装饰器将类名传递给 自己 参数。

# Define class

class Arithmetic:

    @classmethod
    def float_input(class_, 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
    # Code...

n1 = Arithmetic.float_input("Enter your First number: ")
n2 = Arithmetic.float_input("Enter your Second number: ")

还有一个名为 @staticmethod . 如果使用此装饰器,则可以调用该方法,而不必具有 算术 不用定义 自己 在方法签名中。例子:

class Arithmetic:

    @staticmethod
    def float_input(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
    # Code...

n1 = Arithmetic.float_input("Enter your First number: ")
n2 = Arithmetic.float_input("Enter your Second number: ")
AKX
Reply   •   4 楼
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: ")

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

@staticmethod
def float_input(prompt):  # note: no `self`

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

@classmethod
def float_input(cls, prompt):  # `cls` is `Arithmetic` (or its subclass) itself

4使方法只是没有类的正则函数。