เมื่อต้องการค้นหาพื้นที่และปริมณฑลของวงกลมโดยใช้คลาส จะใช้วิธีเชิงวัตถุ ที่นี่ คลาสถูกกำหนด และแอตทริบิวต์ถูกกำหนด ฟังก์ชั่นถูกกำหนดไว้ภายในคลาสที่ดำเนินการบางอย่าง มีการสร้างอินสแตนซ์ของคลาสและใช้ฟังก์ชันเพื่อค้นหาพื้นที่และปริมณฑลของวงกลม
ด้านล่างนี้เป็นการสาธิตสำหรับสิ่งเดียวกัน -
ตัวอย่าง
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'
- ใช้เพื่อคำนวณพื้นที่และปริมณฑลของวงกลมตามลำดับ
- อินสแตนซ์ของคลาสนี้ถูกสร้างขึ้น
- ป้อนค่ารัศมีและดำเนินการกับรัศมีนั้น
- ข้อความและเอาต์พุตที่เกี่ยวข้องจะแสดงบนคอนโซล