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

ความแตกต่างระหว่าง self และ __init__ ใน Python Class

self

self ใช้แทน Instance ของคลาส ใช้ Keyword self เข้าถึง Attributes และ Methods ของคลาสใน Python

__init__ Method

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

ตัวอย่าง: คำนวณค่าใช้จ่ายสนามรูปสี่เหลี่ยม

class Rectangle:
    def __init__(self, length, breadth, unit_cost=0):
        self.length = length
        self.breadth = breadth
        self.unit_cost = unit_cost
    def get_area(self):
        return self.length * self.breadth
    def calculate_cost(self):
        area = self.get_area()
        return area * self.unit_cost

# breadth=120, length=160, cost=2000 per sq unit
r = Rectangle(160, 120, 2000)
print("Area of Rectangle: %s sq units" % (r.get_area()))
print("Cost of rectangular field: Rs.%s" % (r.calculate_cost()))

ผลลัพธ์

Area of Rectangle: 19200 sq units
Cost of rectangular field: Rs.38400000