Python 程式來建立類並計算圓形的面積和周長
當需要使用類、面向物件方法來求圓的面積和周長時。在此,定義了一個類,並定義了屬性。類中定義的一些函式用來執行特定操作。建立類的例項,並使用該函式來求圓的面積和周長。
以下是演示過程 −
示例
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”等函式。
- 這些分別用來計算圓的面積和周長。
- 建立該類的例項。
- 輸入半徑的值,並對其執行操作。
- 相關訊息和輸出顯示在控制檯上。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP