+ 1
Static Methods
Static Methods Complete the given code to define a static add() method for the Calculator class, which returns the sum of its parameters. The code takes two numbers as input, and should return their sum using the Calculator class's add() method. class Calculator: #your code goes here n1 = int(input()) n2 = int(input()) print(Calculator.add(n1, n2)) what is the answer of this?
9 Respostas
+ 8
class Calculator:
@staticmethod
def add(a1, a2):
return a1 + a2
n1 = int(input())
n2 = int(input())
print(Calculator.add(n1, n2))
0
What code you have written so far ?
Also can you please mention the language in tags.
And i see you have completed 2 python courses , so what exactly you don't understand here ?
0
Maksat Ramazanov if called as a static method, you doesn't need to have first 'self' argument...
'self' argument should only be used for instances methods... so your code only works by creating first an instance of Calculator:
calc = Calculator
print(calc.add(n1, n2))
Marite
you only need to add the static method as:
class Calculator:
@staticmethod
def add(v1, v2):
return v1 + v2
0
Hi
0
How to define a class and objects in java language
0
The code defines a class called Shape and within it defines a static method called area. The area method takes two arguments, w and h, and returns their multiplication. In the main part of the code, the user is prompted to input two integers for the width and height of the shape. These values are then passed as arguments to the Shape class's area method, which computes and returns their multiplication. Finally, the result is printed to the console. The @staticmethod decorator is used to mark the area method as a static method, meaning that it can be called on the class itself rather than on an instance of the class.
- 1
Maksat Ramazanov what do your code in fact is using 'add' as a class method, so first (unused) argument is set to class rather than instance (when called from an instance) ^^
- 3
def add(self, n1, n2):
return n1+n2
# Don't create instance of an object.
# Because it's static method