Python Creating a Class to Implement Addition, Subtraction, Multiplication, and Division of Numbers

Document 对象参考手册Python3 Examples

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())

Code explanation:

  1. __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。
  2. addThe method returnsself.num1andself.num2the sum of.
  3. subtractThe method returnsself.num1andself.num2the difference of.
  4. multiplyThe method returnsself.num1andself.num2the product of.
  5. 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.0

Document 对象参考手册Python3 Examples

Other extensions