I have created a Python class:
class calculator:
def addition(self,x,y):
added = x + y
print(added)
def subtraction(self,x,y):
sub = x - y
print(sub)
def multiplication(self,x,y):
mult = x * y
print(mult)
def division(self,x,y):
div = x / y
print(div)
Now when I am calling the function like this:
calculator.addition(2,3)
I am getting an error:
addition() missing 1 required positional argument: 'y'
What is the problem? What could be the solution so that I can call it like addition(2,3)
?
Python' classes have three types of methods:
The instance method must pass the instance object as the first parameter to the method, which is
self
, like:The class method use
classmethod
decorator and must pass the class object as the first parameter to the method, which iscls
, like:The static method doesn’t matter, just add an
staticmethod
decorator, like:So, the last two ways can be your answer if you just want to call with a class object like
calculator.addition(2, 3)
.