You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发Python计算器时出现NameError: name 'add' is not defined错误求助

解决NameError: name 'add' is not defined错误(Python计算器)

你的错误根源在于:add、subtract等方法是Calculator类的实例方法,不能直接作为全局函数调用。必须先创建Calculator类的实例,通过实例来调用这些方法;或者调整代码结构,把这些方法改为全局函数。

方案一:优化Calculator类并正确调用实例方法

首先简化Calculator类的设计(你的__init__参数冗余,不需要把choice、num1等都作为实例属性),然后在solve函数中创建类的实例,通过实例调用计算方法:

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  6 23:32:23 2023

@author: John
"""

class Calculator:
    # 简化__init__,不需要多余参数
    def __init__(self):
        pass
        
    def add(self, x, y):
        return x + y
    
    def subtract(self, x, y):
        return x - y
    
    def multiply(self, x, y):
        return x * y
    
    def divide(self, x, y):
        # 新增除零判断,避免运行时错误
        if y == 0:
            return "Error: Cannot divide by zero"
        return x / y

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
    
def solve():
    # 创建Calculator实例
    calc = Calculator()
    
    while True:
        choice = input("Enter choice(1/2/3/4): ")

        if choice in ('1', '2', '3', '4'):
            try:
                num1 = float(input("Enter first number: "))
                num2 = float(input("Enter second number: "))
            except ValueError:
                print("Invalid input. Please enter a number.")
                continue

            if choice == '1':
                print(num1, "+", num2, "=", calc.add(num1, num2))

            elif choice == '2':
                print(num1, "-", num2, "=", calc.subtract(num1, num2))

            elif choice == '3':
                print(num1, "*", num2, "=", calc.multiply(num1, num2))

            elif choice == '4':
                print(num1, "/", num2, "=", calc.divide(num1, num2))
        
            next_calculation = input("Let's do next calculation? (yes/no): ")
            if next_calculation == "no":
               break
        else:
            print("Invalid Input")
solve()

方案二:直接使用全局函数(无需类)

如果不需要面向对象的设计,可以把计算方法直接定义为全局函数,这样solve中就能直接调用:

# -*- coding: utf-8 -*-
"""
Created on Mon Feb  6 23:32:23 2023

@author: John
"""

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    if y == 0:
        return "Error: Cannot divide by zero"
    return x / y

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
    
def solve():
    while True:
        choice = input("Enter choice(1/2/3/4): ")

        if choice in ('1', '2', '3', '4'):
            try:
                num1 = float(input("Enter first number: "))
                num2 = float(input("Enter second number: "))
            except ValueError:
                print("Invalid input. Please enter a number.")
                continue

            if choice == '1':
                print(num1, "+", num2, "=", add(num1, num2))

            elif choice == '2':
                print(num1, "-", num2, "=", subtract(num1, num2))

            elif choice == '3':
                print(num1, "*", num2, "=", multiply(num1, num2))

            elif choice == '4':
                print(num1, "/", num2, "=", divide(num1, num2))
        
            next_calculation = input("Let's do next calculation? (yes/no): ")
            if next_calculation == "no":
               break
        else:
            print("Invalid Input")
solve()

关键说明

  • 实例方法必须通过类的实例(比如calc.add())调用,因为这类方法依赖于类的实例对象(即使你的方法里没用到self,Python也会自动传递实例作为第一个参数)。
  • 方案二更适合简单的计算器场景,方案一适合后续需要扩展更多功能(比如记录计算历史)的面向对象设计。

内容的提问来源于stack exchange,提问作者Moth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 20:50:29