问题是您没有创建
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: ")