계산기 연산을 수행하는 클래스를 만들어야 할 때는 객체 지향 프로그래밍 방식을 활용하는 것이 가장 효과적입니다. 이 방식에서는 하나의 클래스를 정의하고 그 안에 속성(데이터)과 메서드(기능)를 함께 담아 관리합니다. 덧셈, 뺄셈, 곱셈, 나눗셈 같은 연산은 각각의 메서드로 구현하며, 클래스의 인스턴스를 생성한 뒤 해당 메서드들을 호출하여 계산기를 실제로 동작시킬 수 있습니다.
아래 예제를 통해 구체적인 구현 방법을 살펴보겠습니다.
예제 코드
class calculator_implementation():
def __init__(self,in_1,in_2):
self.a=in_1
self.b=in_2
def add_vals(self):
return self.a+self.b
def multiply_vals(self):
return self.a*self.b
def divide_vals(self):
return self.a/self.b
def subtract_vals(self):
return self.a-self.b
input_1 = int(input("Enter the first number: "))
input_2 = int(input("Enter the second number: "))
print("The entered first and second numbers are : ")
print(input_1, input_2)
my_instance = calculator_implementation(input_1,input_2)
choice=1
while choice!=0:
print("0. Exit")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
choice=int(input("Enter your choice... "))
if choice==1:
print("The computed addition result is : ",my_instance.add_vals())
elif choice==2:
print("The computed subtraction result is : ",my_instance.subtract_vals())
elif choice==3:
print("The computed product result is : ",my_instance.multiply_vals())
elif choice==4:
print("The computed division result is : ",round(my_instance.divide_vals(),2))
elif choice==0:
print("Exit")
else:
print("Sorry, invalid choice!")
print()실행 결과
Enter the first number: 70 Enter the second number: 2 The entered first and second numbers are : 70 2 0. Exit 1. Addition 2. Subtraction 3. Multiplication 4. Division Enter your choice... 1 The computed addition result is : 72 0. Exit 1. Addition 2. Subtraction 3. Multiplication 4. Division Enter your choice... 2 The computed subtraction result is : 68 0. Exit 1. Addition 2. Subtraction 3. Multiplication 4. Division Enter your choice... 3 The computed product result is : 140 0. Exit 1. Addition 2. Subtraction 3. Multiplication 4. Division Enter your choice... 4 The computed division result is : 35.0 0. Exit 1. Addition 2. Subtraction 3. Multiplication 4. Division Enter your choice... 0 Exit
코드 설명
- 먼저 'calculator_implementation'이라는 이름의 클래스를 정의합니다. 이 클래스에는 'add_vals', 'subtract_vals', 'multiply_vals', 'divide_vals'라는 네 개의 메서드가 포함되어 있습니다.
- 각 메서드는 각각 덧셈, 뺄셈, 곱셈, 나눗셈 연산을 수행하도록 구현되어 있습니다.
- '__init__' 생성자 메서드는 두 개의 숫자를 입력받아 인스턴스 변수 'self.a'와 'self.b'에 저장합니다.
- 사용자로부터 두 개의 숫자 값을 입력받은 후, 이 값들을 전달하여 클래스의 인스턴스를 생성합니다.
- while 반복문과 조건문을 활용해 사용자가 원하는 연산을 선택할 수 있는 메뉴 형태의 인터페이스를 제공하며, 0을 입력하면 프로그램이 종료됩니다.
- 나눗셈 결과는 'round()' 함수를 사용해 소수점 둘째 자리까지 반올림하여 표시됩니다.
- 연산 결과와 관련된 메시지들이 콘솔 화면에 출력됩니다.
이처럼 파이썬의 클래스를 활용하면 관련된 데이터와 기능을 하나의 단위로 묶어 관리할 수 있어, 코드의 재사용성과 유지보수성이 크게 향상됩니다. 필요에 따라 거듭제곱, 나머지 연산 등 새로운 메서드를 추가하는 방식으로 계산기 기능을 확장할 수도 있습니다.