1

I'm running Python 3.9 in Pycharm. I am trying to run this code where I create a function that does addition. I am getting an error that says unresolved reference and for some reason, it is telling me that add is not defined. I've tried rearranging the order of functions to see if that would change anything and it did not.

Python code

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
TyisaGeek
  • 11
  • 1
  • Try `self.add`. – Mark Ransom Apr 25 '21 at 01:24
  • Please post code, error messages, and terminal output as **TEXT** – Gino Mempin Apr 25 '21 at 01:29
  • Also, since you seem to be not using `self` anywhere, you might want to read this and understand what's it for when creating and using classes: [What is the purpose of the word 'self'?](https://stackoverflow.com/a/31096552/2745495). You shouldn't need that `global first, second, total` in there. – Gino Mempin Apr 25 '21 at 01:33
  • The answer by Suyog Shimp is correct. I would say that defining the add function outside the class would also work. – Sergio Pulgarin Apr 25 '21 at 01:40

3 Answers3

1

You may miss @staticmethod decorator at top of the method add, Also you must call the method by self as self.add(x, y)

like -

@staticmethod
def add(x, y):
   ...

Otherwise, you can add self as the first parameter

def add(self, x, y):
   ...
Suyog Shimpi
  • 706
  • 1
  • 8
  • 16
0

Yeah You'll get an error as add is not defined, you need to change it to: Addition.add

0

add is a function and not a method looking from your screenshot, it has to be a member of the class for the class to know that add is present. There are a couple of ways to achieve this.

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

or

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

or

@classmethod
def add(cls, x, y):
    return x + y

then on line 42 from your screenshot, you will do

total = self.add(first, second)

But I am looking at your class and I am worried on why you are using globals, and not class variables or instance variables?

and since process calls add, and add has no link with any attribute of the class, it will be ideal to make add either a static method or take it out of the class to a make it a function on it's own.

Look into OOP, check out this link https://realpython.com/python3-object-oriented-programming/