Devdit
 

__init__ python คืออะไร ใช้ทำอะไร

7.6K

__init__ python คือลักษณะเดียวกับ constructor method ของภาษาอื่นๆ ทำให้สามารถกำหนดค่า arguments หรือ parameters ลงใน class ตอนที่สร้าง instance ได้เลย ทำงานร่วมกับ self สามารถเขียนโปรแกรมได้ดังนี้

 

ตัวอย่าง __init__ python คืออะไร ใช้ทำอะไร

class Demo:
  def __init__(self, name):  
    self.name = name
  def hello(self):
    print('Hello',self.name)

demo = Demo('Devdit')
demo.hello()

ผลลัพธ์

Hello Devdit

คำอธิบาย

__init__ python จากตัวอย่างโค้ดใน class Demo มี method คือ def __init__(self, name) หมายความว่าสามารถสร้าง instance จาก class Demo พร้อมกำหนดค่า arguments name ได้เลยตอนที่สร้าง เช่น Demo('Devdit') ลักษณะการทำงานคล้ายกับ constructor method ของภาษาอื่นๆ 

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