Static Methods | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
+ 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?

7th Jul 2021, 1:43 PM
Eduards
9 ответов
+ 8
class Calculator: @staticmethod def add(a1, a2): return a1 + a2 n1 = int(input()) n2 = int(input()) print(Calculator.add(n1, n2))
4th Sep 2021, 10:19 PM
Khomi TAKAYANAGI
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 ?
7th Jul 2021, 3:35 PM
Abhay
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
7th Jul 2021, 6:31 PM
visph
7th Jul 2021, 6:37 PM
visph
0
Hi
11th Mar 2022, 12:59 PM
Anmol Thakur
0
How to define a class and objects in java language
11th Mar 2022, 1:00 PM
Anmol Thakur
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.
20th Oct 2023, 7:40 AM
Elumalai Nikhilesh Krishna
- 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) ^^
7th Jul 2021, 6:35 PM
visph
- 3
def add(self, n1, n2): return n1+n2 # Don't create instance of an object. # Because it's static method
7th Jul 2021, 1:50 PM
Maksat Ramazanov
Актуальное сегодня
Bash