我是python的新手,所以我决定使用函数创建一个基本的计算器应用程序,但是,每当我尝试调用我的一个计算函数时,它都说它是一个未解析的函数引用。我环顾四周,但我不确定发生了什么。
我的代码:
class BasicCalculator:
# define functions
def add(x, y):
"""This function adds two numbers"""
return x + y
def subtract(x, y):
"""This function subtracts two numbers"""
return x - y
def multiply(x, y):
"""This function multiplies two numbers"""
return x * y
def divide(x, y):
"""This function divides two numbers"""
return x / y
def power(x, y):
"""This function does a power of two numbers"""
return x ** y
if __name__ == '__main__':
print("Select an operator")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Power")
left = int(input("Enter your left number: "))
choice = int(input("Select your operator(1, 2, 3, 4): "))
right = int(input("Select your right number: "))
if choice == '1':
#Error is here, it says "Unresolved reference 'add'"
print(add(left, right))
else:
print("Invalid input")
答案 0 :(得分:0)
函数add
在类BasicCalculator
中定义。你需要做BasicCalculator.add()
。您也可以在课堂外定义add
。
基本上,只需将此行print(add(left, right))
更改为print(BasicCalculator.add(left, right))
此外,值得检查其他两个变量(左和右)是否已正确初始化。因此,将if choice == '1':
更改为if (choice == '1') and (left is not None) and (right is not None):
答案 1 :(得分:0)
你的函数是在我认为的类中定义的 - 尽管你在这里写的缩进并不完全一致。你可以尝试: -
答案 2 :(得分:0)
制作计算器实例
choice = input("Select your operator(1, 2, 3, 4): ") # Not an int
calc = BasicCalculator()
if choice == '1': # You are comparing strings, not ints
print(calc.add(left, right))
答案 3 :(得分:0)
您的代码有4个问题需要修复:
1st:您需要添加self
作为BasicCalculator
类中所有方法的第一个参数,self
是对当前实例的引用班级:
class BasicCalculator:
# define functions
def add(self, x, y): # self must be the first argument
"""This function adds two numbers"""
return x + y
# ...
第二名:您需要实例化您的课程:
calculator = BasicCalculator()
第3名:按照以下方式调用您的函数:
calculator.add(left, right)
第4名:您需要修正if
声明:
if choice == 1: # not '1', because choice is an integer (choice = int(input("...")))
所有在一起:您的代码现在应如下所示:
class BasicCalculator:
# define functions
def add(self, x, y):
"""This function adds two numbers"""
return x + y
def subtract(self, x, y):
"""This function subtracts two numbers"""
return x - y
def multiply(self, x, y):
"""This function multiplies two numbers"""
return x * y
def divide(self, x, y):
"""This function divides two numbers"""
return x / y
def power(self, x, y):
"""This function does a power of two numbers"""
return x ** y
if __name__ == '__main__':
print("Select an operator")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Power")
left = int(input("Enter your left number: "))
choice = int(input("Select your operator(1, 2, 3, 4): "))
right = int(input("Select your right number: "))
calculator = BasicCalculator()
if choice == 1:
print(calculator.add(left, right))
else:
print("Invalid input")