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

Python OOP中NameError:名称'add'未定义问题求助

Fixing the NameError and Other Issues in Your Complex Number Class

Hey there! Let's work through your problem and get your Complex number class working properly.

First: The NameError You're Seeing

The immediate issue is that add isn't a global function—it's an instance method of your Complex class. Instance methods need to be called on an instance of the class, because Python automatically passes the instance as the first self parameter.

Instead of writing:

add(x, y)

You need to call it like this:

print(x.add(y))

Or, since addition is commutative, y.add(x) would work too.

Next: Fixing the add Method's Return Value

Right now your add method tries to return "%d" % summ, but summ is a Complex object—you can't format it directly with %d. Instead, either:

  • Return the Complex instance itself, then use its __str__ method when printing, or
  • Format the string using the instance's r and i attributes.

Here's a clean corrected version of the add method:

def add(self, other):
    summ = Complex(self.r + other.r, self.i + other.i)
    return f"Sum is {summ}"

Or, if you want to return the Complex instance for further use (like chaining operations):

def add(self, other):
    return Complex(self.r + other.r, self.i + other.i)

Then you'd call it like:

sum_result = x.add(y)
print(f"Sum is {sum_result}")

Other Critical Fixes for Your Class

Your multiply and divide methods have incorrect complex number math—let's fix those to match real-world rules:

  1. Multiplication: The correct formula for (a+bi)(c+di) is (ac - bd) + (ad + bc)i
  2. Division: The correct formula is [(ac + bd)/(c² + d²)] + [(bc - ad)/(c² + d²)]i

Here's the corrected multiply method:

def multiply(self, other):
    real_part = self.r * other.r - self.i * other.i
    imag_part = self.r * other.i + self.i * other.r
    return Complex(real_part, imag_part)

And the corrected divide method (we'll skip division-by-zero handling for simplicity, but you could add a check later):

def divide(self, other):
    denominator = other.r ** 2 + other.i ** 2
    real_part = (self.r * other.r + self.i * other.i) / denominator
    imag_part = (self.i * other.r - self.r * other.i) / denominator
    return Complex(real_part, imag_part)

Full Corrected Code

Putting it all together, here's your updated, functional code:

class Complex(object):
    def __init__(self, r=0, i=0):
        self.r = r
        self.i = i

    def __str__(self):
        return f"{self.r} + i{self.i}"

    def add(self, other):
        summ = Complex(self.r + other.r, self.i + other.i)
        return f"Sum is {summ}"

    def dif(self, other):
        dif = Complex(self.r - other.r, self.i - other.i)
        return dif

    def multiply(self, other):
        real_part = self.r * other.r - self.i * other.i
        imag_part = self.r * other.i + self.i * other.r
        return Complex(real_part, imag_part)

    def divide(self, other):
        denominator = other.r ** 2 + other.i ** 2
        real_part = (self.r * other.r + self.i * other.i) / denominator
        imag_part = (self.i * other.r - self.r * other.i) / denominator
        return Complex(real_part, imag_part)

x = Complex()
x.r = int(input("Type in real part of x: \n"))
x.i = int(input("Type in imaginary part of x: \n"))
print(x, "\n")

y = Complex()
y.r = int(input("Type in real part of y: \n"))
y.i = int(input("Type in imaginary part of y: \n"))
print(y, "\n")

# Call add correctly
print(x.add(y))
# Example usage of other methods
print(f"Difference is {x.dif(y)}")
print(f"Product is {x.multiply(y)}")
print(f"Quotient is {x.divide(y)}")

Key OOP Takeaways for Python Newbies

  • Instance methods always take self as the first parameter, and are called on an instance (like x.add(y)), not as standalone functions.
  • When working with custom classes, make sure your logic matches real-world rules (like complex number operations) to get correct results.
  • The __str__ method is your friend—it controls how your objects are printed, making debugging and output much cleaner.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:54:57