使用類查詢矩形面積的 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”方法。
- 它還有一個方法,用於根據特定引數計算矩形的面積。
- 建立了此類的例項。
- 透過傳遞所需的引數呼叫計算面積的函式。
- 它在控制檯上顯示為輸出。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP