Python Write a class to perform addition, subtraction, multiplication, and division of numbers
We will write a class namedCalculatorclass, which contains four methods:add(addition),subtract(subtraction),multiply(multiplication) anddivide(division). These methods will accept two numbers as parameters and return the corresponding operation result.
Example
class Calculator:
def add(self, a, b):
return a + b
def subtract(self, a, b):
return a - b
def multiply(self, a, b):
return a * b
def divide(self, a, b):
if b == 0:
raise ValueError("Cannot divide by zero.")
return a / b
def add(self, a, b):
return a + b
def subtract(self, a, b):
return a - b
def multiply(self, a, b):
return a * b
def divide(self, a, b):
if b == 0:
raise ValueError("Cannot divide by zero.")
return a / b
Code analysis:
add(self, a, b): This method accepts two parametersaandb, and returns their sum.subtract(self, a, b): This method accepts two parametersaandb, and returns their difference.multiply(self, a, b): This method accepts two parametersaandb, and returns their product.divide(self, a, b): This method accepts two parametersaandb, and returns their quotient. Ifbis 0, it will throw aValueErrorexception, because the divisor cannot be zero.
Output result:
Example
calc = Calculator()
print(calc.add(10, 5)) # Output: 15
print(calc.subtract(10, 5)) # Output: 5
print(calc.multiply(10, 5)) # Output: 50
print(calc.divide(10, 5)) # Output: 2.0
print(calc.add(10, 5)) # Output: 15
print(calc.subtract(10, 5)) # Output: 5
print(calc.multiply(10, 5)) # Output: 50
print(calc.divide(10, 5)) # Output: 2.0
This class can be used to perform basic mathematical operations, and ensures the safety of division through exception handling.
Other extensions
Python3 Examples