Python define a class containing multiple methods, each method implements a different mathematical operation

Document 对象参考手册Python3 Examples

We will define a class namedMathOperationsThe class contains multiple methods, each method implements a different mathematical operation, such as addition, subtraction, multiplication, and division.

Example

class MathOperations:
    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:
            return "Error: Division by zero is not allowed."
        return a / b

Code explanation:

  • 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, an error message is returned because division by zero is not allowed.

Output result:

Example

math_ops = MathOperations()
print(math_ops.add(10, 5))        # Output: 15
print(math_ops.subtract(10, 5))   # Output: 5
print(math_ops.multiply(10, 5))   # Output: 50
print(math_ops.divide(10, 5))     # Output: 2.0
print(math_ops.divide(10, 0))     # Output: Error: Division by zero is not allowed.

Document 对象参考手册Python3 Examples

Other extensions