Python Create a Class to Implement Number Arithmetic Operations
-- Learn not just technology, but dreams!
Python3 Tutorial
Python3 Advanced Tutorial
Machine Learning
Python3 Tutorial - Create a Class for Arithmetic Operations
In this tutorial, we will learn how to create a Python class that implements basic arithmetic operations: addition, subtraction, multiplication, and division. This is a fundamental example of object-oriented programming in Python.
Class Definition
First, let's define a Calculator class with methods for each arithmetic operation:
class Calculator:
def __init__(self, a, b):
self.a = a
self.b = b
def add(self):
return self.a + self.b
def subtract(self):
return self.a - self.b
def multiply(self):
return self.a * self.b
def divide(self):
if self.b == 0:
return "Error: Division by zero"
return self.a / self.b
Usage Example
Here's how to use our Calculator class:
# Create a Calculator instance
calc = Calculator(10, 5)
# Perform operations
print("Addition:", calc.add()) # Output: 15
print("Subtraction:", calc.subtract()) # Output: 5
print("Multiplication:", calc.multiply()) # Output: 50
print("Division:", calc.divide()) # Output: 2.0
Advanced Example with Error Handling
Let's enhance our Calculator class with better error handling:
class AdvancedCalculator:
def __init__(self, a, b):
self.a = a
self.b = b
def add(self):
"""Perform addition"""
return self.a + self.b
def subtract(self):
"""Perform subtraction"""
return self.a - self.b
def multiply(self):
"""Perform multiplication"""
return self.a * self.b
def divide(self):
"""Perform division with error handling"""
try:
if self.b == 0:
raise ValueError("Cannot divide by zero")
return self.a / self.b
except ValueError as e:
return f"Error: {str(e)}"
def get_results(self):
"""Return all operation results as a dictionary"""
return {
'add': self.add(),
'subtract': self.subtract(),
'multiply': self.multiply(),
'divide': self.divide()
}
Summary
In this tutorial, we have created a Calculator class that demonstrates the basic principles of object-oriented programming in Python. The class encapsulates the data (numbers) and behavior (arithmetic operations) together, making the code more organized and reusable.
Key concepts covered:
- Class definition and initialization
- Instance methods
- Error handling for division by zero
- Object instantiation and method calls
YouTip