'__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)
Solution 1:[1]
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.
Solution 2:[2]
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)
Solution 3:[3]
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"):
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | SDS0 |
Solution 2 | Pratik Gandhi |
Solution 3 | dev-gm |