RadioTune
RadioTune

Reputation: 21

__init__() missing 1 required positional argument it reads self as a parameter

I'm new at programming and I'm learning Python. The code should be very simple. The goal should be implement a calculator that does additions between numbers. It returns this error:

init() missing 1 required positional argument: 'number_2'

So it's like it reads self as a parameter, but I can't figure out why. I'm using Linux Ubuntu 19 as operative system. Here's my code:

class Calculator:
    def __init__(self, number_1, number_2):
        self.number_1=number_1
        self.number_2=number_2

    def add(self):
        print(f"{number_1}+{number_2}={number_1+number_2}")

if __name__=="__main__":
    c=Calculator('Casio')
    c.add(2,3)

Upvotes: 2

Views: 1242

Answers (3)

dev-gm
dev-gm

Reputation: 63

When you are initializing the object 'c', you are running the init method, and you therefore need to pass in both parameters to the init method. So, you are required to give both 'number_1' and 'number_2' when you create the object. You passed in only'Casio', which python is interpreting as 'number_1'. Python is also interpreting that there is no 'number_2'. Here are some solutions: 1: You could make the add() function have the two arguments that init has ('number_1' and 'number_2') and have the only arguments for init be self and 'name'. Then, you could have the init method only do self.name = name and nothing else. 2: You could make the arguments 'number_1' and 'number_2' optional by making a default variable for them if you do not enter it:

def __init__(self, number_1="1", number_2="2"):

Upvotes: 0

Pratik
Pratik

Reputation: 1399

You have to pass parameters to the add function and not to __init__ which instantiates the class.

class Calculator:
    def __init__(self, name):
        self.name=name

    def add(self, number_1, number_2):
        print(f"{number_1}+{number_2}={number_1+number_2}")

if __name__=="__main__":
    c=Calculator('Casio')
    c.add(2,3)

Upvotes: 1

SDS0
SDS0

Reputation: 520

It isn't reading self as a parameter here, but 'Casio' which it is storing as number_1. As the error message reads, it is missing number 2. If you want add() to be able to take arbitrary values, you will need to add them as arguments to that method rather than to the __init__() function.

Upvotes: 1

Related Questions