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

Constructor __init__ ใน Python ทำงานอย่างไร

__init__

"__init__" เป็น Reserved Method ในคลาส Python เรียกว่า Constructor ในแนวคิด OOP เรียกเมื่อสร้างออบเจ็กต์จากคลาส ให้คลาส Initialize Attributes ได้

การใช้งาน

สมมติสร้างคลาส Car มี Attributes: color, model, speed และ Methods: start, accelerate, change_gear

ตัวอย่าง

class Car(object):
    def __init__(self, model, color, speed):
        self.color = color
        self.speed = speed
        self.model = model
    def start(self):
        print("started")
    def accelerate(self):
        print("accelerating...")
    def change_gear(self, gear_type):
        print("gear changed")

ใช้ __init__ เพื่อ Initialize Class Attributes