클래스를 이용하여 사각형의 넓이를 구해야 할 때 객체지향 방법을 사용한다. 여기에서 클래스가 정의되고 속성이 정의됩니다. 함수는 특정 작업을 수행하는 클래스 내에서 정의됩니다. 클래스의 인스턴스가 생성되고 함수를 사용하여 사각형의 면적을 찾습니다.
아래는 동일한 데모입니다 -
예시
class shape_rectangle():
def __init__(self,my_length, my_breadth):
self.length = my_length
self.breadth = my_breadth
def calculate_area(self):
return self.length*self.breadth
len_val = 6
bread_val = 45
print("The length of the rectangle is : ")
print(len_val)
print("The breadth of the rectangle is : ")
print(bread_val)
my_instance = shape_rectangle(len_val,bread_val)
print("The area of the rectangle : ")
print(my_instance.calculate_area())
print() 출력
The length of the rectangle is : 6 The breadth of the rectangle is : 45 The area of the rectangle : 270
설명
- 'shape_rectangle'이라는 클래스가 정의되었습니다.
- 값을 초기화하는 'init' 메소드가 있습니다.
- 특정 매개변수가 주어지면 직사각형의 면적을 계산하는 방법도 있습니다.
- 이 클래스의 인스턴스가 생성됩니다.
- 필요한 매개변수를 전달하여 면적을 계산하는 함수를 호출합니다.
- 콘솔에 출력으로 표시됩니다.