gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
write a sample python class
- User
write a sample python class
- Assistant
Certainly! Below is a simple example of a Python class that represents a basic calculator. This calculator can perform addition, subtraction, multiplication, and division.
class Calculator: def __init__(self): """Initialize the calculator with a result set to zero.""" self.result = 0 def add(self, value): """Add a number to the current result.""" self.result += value return self.result def subtract(self, value): """Subtract a number from the current result.""" self.result -= value return self.result def multiply(self, value): """Multiply the current result by a number.""" self.result *= value return self.result def divide(self, value): """Divide the current result by a number. Raises an error if value is zero.""" if value == 0: raise ValueError("Cannot divide by zero") self.result /= value return self.result def reset(self): """Reset the calculator result to zero.""" self.result = 0 return self.result # Example usage: calc = Calculator() print(calc.add(5)) # Output: 5 print(calc.subtract(2)) # Output: 3 print(calc.multiply(4)) # Output: 12 print(calc.divide(3)) # Output: 4.0 print(calc.reset()) # Output: 0