1

Some context, I have a similar little more complex function which is under a class, and receives the same error. I do think this is just a concept problem that I have with functions.

Code:

def add(self, atr):
print(self.atr)

add("me")

Error:

Traceback (most recent call last):


File "problem_file_2.py", line 5, in <module>
    add("me")

TypeError: add() missing 1 required positional argument: 'atr'
  • Could you try to make an example that demonstrates the behaviour? As it is we can not see if you have any indentation problems, and that simple call to `add` seems suspicious since it looks like a function call, not like a method call. – Matthias Feb 02 '21 at 09:41

2 Answers2

0

When you have a function under class like one given below, self acts as the context of the instance of the class.

class Number:
    def __init__(self, value):
        self.value = value
        
    def add(self, atr):
        self.value += atr

In order to create an instance, you must call the constructor.

n = Number(5)
n.add(5)
print(n.value)

This will output

10

You are getting the error because you never created the instance.

Vishnudev Krishnadas
  • 10,679
  • 2
  • 23
  • 55
0
class A:
  def add(self, atr):
    self.atr = atr
    print(self.atr)

A.add("me") # error
A().add("me") # works

A class is a type. More objects can be of same type.

a=A() makes an object/instance of type A.

self is such an object of type A.

a.add(atr) is like A.add(a,atr).

Roland Puntaier
  • 3,250
  • 30
  • 35