Python OOP中NameError:名称'add'未定义问题求助
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
Complexinstance itself, then use its__str__method when printing, or - Format the string using the instance's
randiattributes.
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:
- Multiplication: The correct formula for
(a+bi)(c+di)is(ac - bd) + (ad + bc)i - 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
selfas the first parameter, and are called on an instance (likex.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

