파이썬에서 클래스를 활용해 원의 넓이와 둘레를 구하려면 객체지향 프로그래밍(OOP) 방식을 사용하는 것이 좋습니다. 이 방식에서는 하나의 클래스를 정의하고, 그 안에 속성(변수)과 동작(메서드)을 함께 담아 관리할 수 있습니다.
구체적인 절차는 다음과 같습니다.
- 원의 반지름을 저장할 클래스를 정의합니다.
- 생성자(
__init__)에서 반지름 값을 초기화합니다. - 넓이와 둘레를 각각 계산하는 메서드를 클래스 내부에 작성합니다.
- 클래스의 인스턴스(객체)를 생성한 뒤, 메서드를 호출하여 결과를 출력합니다.
사용되는 수학 공식은 다음과 같습니다.
- 원의 넓이: π × r²
- 원의 둘레: 2 × π × r
예제 코드
import math
class circle_compute():
def __init__(self,my_radius):
self.radius=my_radius
def area_calculate(self):
return math.pi*(self.radius**2)
def perimeter_calculate(self):
return 2*math.pi*self.radius
my_result = int(input("Enter the radius of circle..."))
my_instance = circle_compute(my_result)
print("The radius entered is :")
print(my_result)
print("The computed area of circle is ")
print(round(my_instance.area_calculate(),2))
print("The computed perimeter of circle is :")
print(round(my_instance.perimeter_calculate(),2))실행 결과
Enter the radius of circle...7 The radius entered is : 7 The computed area of circle is 153.94 The computed perimeter of circle is : 43.98
코드 설명
circle_compute라는 이름의 클래스를 정의하며, 그 안에area_calculate(넓이 계산)와perimeter_calculate(둘레 계산) 메서드가 포함됩니다.- 생성자
__init__는 객체 생성 시 전달받은 반지름 값을self.radius에 저장합니다. area_calculate메서드는math.pi를 이용해 π × r² 공식으로 넓이를 반환합니다.perimeter_calculate메서드는 2 × π × r 공식으로 둘레를 반환합니다.input()함수로 사용자에게 반지름 값을 입력받고, 이를 정수로 변환한 뒤 클래스 인스턴스를 생성합니다.round()함수를 사용해 소수점 둘째 자리까지 반올림하여 결과를 콘솔에 출력합니다.
이처럼 클래스를 사용하면 반지름 데이터와 관련 연산을 하나의 단위로 묶어 관리할 수 있어, 코드의 재사용성과 가독성이 크게 향상됩니다. 필요에 따라 지름, 부채꼴 각도 등 다른 속성과 메서드를 추가하여 확장할 수도 있습니다.