Reputation: 85
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)
?
Upvotes: 1
Views: 12925
Reputation: 169
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:
class calculator:
def addition(self, x, y):
added = x + y
print(added)
c = calculator()
c.addition(2, 3)
The class method use classmethod
decorator and must pass the class object as the first parameter to the method, which is cls
, like:
class calculator:
@classmethod
def addition(cls, x, y):
added = x + y
print(added)
calculator.addition(2, 3)
The static method doesn’t matter, just add an staticmethod
decorator, like:
class calculator:
@staticmethod
def addition(x, y):
added = x + y
print(added)
calculator.addition(2, 3)
So, the last two ways can be your answer if you just want to call with a class object like calculator.addition(2, 3)
.
Upvotes: 5
Reputation: 36
If you just want the function addition write it not as a class methode but as a function.
If you need write «calculator.addition(2,3)» first do calculator = Calculator()
Upvotes: 0
Reputation: 101
You just neet to delete self. Self will be used when you have __init __ function
class calculator:
def addition(x,y):
added = x + y
print(added)
def subtraction(x,y):
sub = x - y
print(sub)
def multiplication(x,y):
mult = x * y
print(mult)
def division(x,y):
div = x / y
print(div)
calculator.addition(2,3)
Upvotes: -1
Reputation: 2017
You have to pass in the self
variable by actually declaring an instance of this class, like this:
myCalculator = calculator()
myCalculator.addition(2,3)
Output should be: 5
Upvotes: 3
Reputation: 181
Please create a instance of the class first:
calculator_instance = calculator()
Then, you can call the function as calculator_instance.addition(2,3)
Upvotes: 1