Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรม Python หาพื้นที่สี่เหลี่ยมผืนผ้าด้วยคลาส

บทนำ

ตัวอย่างง่ายๆ ของการสร้างคลาส Rectangle เพื่อคำนวณพื้นที่สี่เหลี่ยมผืนผ้าจากความยาวและความกว้าง

ตัวอย่างโค้ด

class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        return self.length * self.width

    def perimeter(self):
        return 2 * (self.length + self.width)

# ใช้งาน
length = 6
width = 45

rect = Rectangle(length, width)
print(f"ความยาว: {length}")
print(f"ความกว้าง: {width}")
print(f"พื้นที่: {rect.area()}")
print(f"เส้นรอบวง: {rect.perimeter()}")

ผลลัพธ์

ความยาว: 6
ความกว้าง: 45
พื้นที่: 270
เส้นรอบวง: 102

คำอธิบาย

  • __init__ รับความยาวและความกว้าง
  • area() คืนค่า length × width
  • perimeter() คืนค่า 2(length + width)
  • สร้าง instance แล้วเรียกเมธอด

เพิ่ม Validation

def __init__(self, length, width):
    if length <= 0 or width <= 0:
        raise ValueError("ความยาวและความกว้างต้องมากกว่า 0")
    self.length = length
    self.width = width