Python Creating a Class to Implement Addition, Subtraction, Multiplication, and Division of Numbers
We will create a class namedCalculatorclass, which will contain four methods:add、subtract、multiplyanddivide, used to perform addition, subtraction, multiplication, and division operations respectively.
Example
class Calculator:
def __init__(self, num1, num2):
self.num1 = num1
self.num2 = num2
def add(self):
return self.num1 + self.num2
def subtract(self):
return self.num1 - self.num2
def multiply(self):
return self.num1 * self.num2
def divide(self):
if self.num2 == 0:
return "Error: Division by zero is not allowed."
return self.num1 / self.num2
# Example usage
calc = Calculator(10, 5)
print("Addition:", calc.add())
print("Subtraction:", calc.subtract())
print("Multiplication:", calc.multiply())
print("Division:", calc.divide())
def __init__(self, num1, num2):
self.num1 = num1
self.num2 = num2
def add(self):
return self.num1 + self.num2
def subtract(self):
return self.num1 - self.num2
def multiply(self):
return self.num1 * self.num2
def divide(self):
if self.num2 == 0:
return "Error: Division by zero is not allowed."
return self.num1 / self.num2
# Example usage
calc = Calculator(10, 5)
print("Addition:", calc.add())
print("Subtraction:", calc.subtract())
print("Multiplication:", calc.multiply())
print("Division:", calc.divide())
Code explanation:
__init__The method is the constructor of the class, used to initialize instances of the class. It accepts two parametersnum1andnum2, and assigns them to instance variablesself.num1andself.num2。addThe method returnsself.num1andself.num2the sum of.subtractThe method returnsself.num1andself.num2the difference of.multiplyThe method returnsself.num1andself.num2the product of.divideThe method first checks whetherself.num2is zero. If it is zero, it returns an error message; otherwise, it returnsself.num1divided byself.num2the result.
Output result:
Addition: 15 Subtraction: 5 Multiplication: 50 Division: 2.0Other extensions
Python3 Examples