使用類查詢矩形面積的 Python 程式


當需要使用類查詢矩形的面積時,使用面向物件的的方法。在這裡,定義了一個類,並定義了屬性。在類中定義了執行某些操作的函式。建立了類的例項,並使用這些函式查詢矩形的面積。

下面是對此的演示 -

示例

 即時演示

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”方法。
  • 它還有一個方法,用於根據特定引數計算矩形的面積。
  • 建立了此類的例項。
  • 透過傳遞所需的引數呼叫計算面積的函式。
  • 它在控制檯上顯示為輸出。

更新於: 2021年3月11日

4K+ 瀏覽量

啟動你的 職業生涯

完成課程獲得認證

開始學習
廣告

© . All rights reserved.