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

Python เป็น Object-Oriented หรือ Procedural?

ใช่ Python รองรับทั้ง Object-Oriented และ Procedural Programming เนื่องจากเป็นภาษาโปรแกรมมิ่งระดับสูงที่ออกแบบมาเพื่อวัตถุประสงค์ทั่วไป Python เป็น Multi-paradigm คุณสามารถเขียนโปรแกรมหรือไลบรารีที่เป็น Procedural, Object-Oriented, หรือ Functional ได้ทั้งหมด ขึ้นอยู่กับว่าคุณนิยาม Functional อย่างไร Python มีคุณสมบัติบางอย่างของภาษา Functional

แนวคิด OOP เช่น Classes, Encapsulation, Polymorphism, Inheritance ใน Python ทำให้มันเป็นภาษา Object-Oriented

เช่นเดียวกัน เราสามารถสร้างโปรแกรม Procedural ผ่าน Python โดยใช้ loops, for, while และโครงสร้างควบคุมต่างๆ

ตัวอย่าง OOP

class Rectangle:
    def __init__(self, length, breadth, unit_cost=0):
        self.length = length
        self.breadth = breadth
        self.unit_cost = unit_cost

    def get_perimeter(self):
        return 2 * (self.length + self.breadth)

    def get_area(self):
        return self.length * self.breadth

    def calculate_cost(self):
        area = self.get_area()
        return area * self.unit_cost

# breadth = 120 cm, length = 160 cm, 1 cm^2 = Rs 2000
r = Rectangle(160, 120, 2000)
print("Area of Rectangle: %s cm^2" % (r.get_area()))
print("Cost of rectangular field: Rs. %s" % (r.calculate_cost()))

ผลลัพธ์

Area of Rectangle: 19200 cm^2
Cost of rectangular field: Rs. 38400000