agon_isation
agon_isation

Reputation: 67

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)

Upvotes: 4

Views: 894

Answers (2)

user9614249
user9614249

Reputation:

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.

Upvotes: 2

tangoal
tangoal

Reputation: 769

If add is a method of your class Complex, then you must write x.add(y) instead of add(x, y).

I know that it is confusing in Python. You need always to apply the "self" as first argument of a method, although it is not an argument, but the object whose method you call.

Upvotes: 0

Related Questions