Devdit
 

Python สร้าง constructor method ยังไง

1K

Python สร้าง constructor method ยังไง บทความนี้สอนสร้าง constructor method ด้วยภาษา Python โดย constructor คือ method ที่ทำให้เราสามารถกำหนดค่าตัวแปร หรือ property ได้ตอนสร้าง object สามารถเขียนโปรแกรมได้ดังนี้

 

ตัวอย่าง Python สร้าง constructor method ยังไง

class Example:
  def __init__(self, a, b):
    self.a = a
    self.b = b
  def getValue(self):
    print("a = "+str(self.a)+" / b = "+str(self.b))

example = Example( 4, 10 )
example.getValue()

ผลลัพธ์

a = 4 / b = 10

คำอธิบาย

Python สร้าง constructor method จากตัวอย่างคือ def __init__(self, a, b) รับค่า parameters ที่เป็นตัวแปร property 2 ตัวคือ a และ b จากนั้นแสดงค่าตัวแปรทั้ง 2 ออกสู่หน้าจอด้วย method getValue คือ self.a และ self.b ภาษา Python

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