Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Name "function name" is not defined

I've been attempting to complete one of my subjects for the OOP, but I couldn't manage to figure out what's wrong with the definition of my functions. I'm a newbie in this language, already searched the forums but I couldn't find anything useful.

Error message: Traceback (most recent call last):
File "/home/main.py", line 44, in
add(x, y)
NameError: name 'add' is not defined

This is the program I wrote.

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

def __str__ (self):
   return "%s + i%s" % (self.r, self.i)

def add (self, other):
   summ = Complex()
   summ.r = self.r + other.r
   summ.i = self.i + other.i
   return "Sum is %d" % summ

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

def multiply (self, other):
   multiply = Complex()
   multiply.r = self.r * other.r 
   multiply.i = self.i * other.i
   return "%d" % (-1 * multiply.r * multiply.i)

def divide (self, other):
   divide = Complex()
   divide.r = self.r / other.r
   divide.i = self.i / other.i 
   return "%d" % (divide.r / divide.i)

x = Complex()
y = Complex()
x.r = int(input("Type in real part of x: \n"))
x.i = int(input("Type in imaginary of x: \n"))
print (x, "\n")
y.r = int(input("Type in real part of y: \n"))
y.i = int(input("Type in imaginary of y: \n"))
print (y, "\n")
add(x, y)
like image 762
agon_isation Avatar asked Oct 22 '25 11:10

agon_isation


1 Answers

The add() function is a member of the Complex class but you are calling it on its own.

You need to call it like this

x.add(y)

When a function is a member of a class like below:

class Complex(object):
    def add (self, other):
        # Do stuff

The object the function is called on automatically gets passed as self.

So if you call x.add(y), self will be x and other will be y.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!