Devdit
 

Python OOP สอนเขียนโปรแกรม

851

Python OOP สอนเขียนโปรแกรม บทความนี้สอนสร้าง class, constructor method, method และ property แบบ OOP และเรียกใช้ class ดังกล่าวโดยการสร้าง object หรือ instance ด้วยภาษา Python สามารถเขียนโปรแกรมได้ดังนี้

 

ตัวอย่าง Python OOP สอนเขียนโปรแกรม

class Product:
  def __init__( self, title, price ):
    self.title = title
    self.price = price
  
  def getValue( self ):
    print("Title = "+str(self.title)+" / Price = "+str(self.price))

p1 = Product('Computer', 200)
p2 = Product('Notebook', 180)
p1.getValue()
p2.getValue()

ผลลัพธ์

Title = Computer / Price = 200
Title = Notebook / Price = 180

คำอธิบาย

Python OOP สอน จากตัวอย่างสร้าง class Product พร้อมกับกำหนดค่า และเรียกใช้งาน method getValue โดยมีรายละเอียดดังนี้

1. สร้าง class Product ประกอบด้วย 2 property คือ title, price และ 2 method คือ constructor method กับ getValue

2. constructor method คือ def __init__ ทำหน้าที่รับค่า parameters title และ price

3. method getValue คือ def getValue ทำหน้าที่พิมพ์ค่า title และ price ออกสู่หน้าจอด้วยคำสั่ง print

4. สร้าง object p1 จาก class Product พร้อมกำหนดค่าเริ่มต้นด้วย p1 = Product('Computer', 200)

5. สร้าง object p2 จาก class Product พร้อมกำหนดค่าเริ่มต้นด้วย p2 = Product('Notebook', 180)

6. แสดงค่าออกสู่หน้าจอด้วย method getValue จาก p1.getValue() และ p2.getValue()

แก้ไข 1 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ