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

การสร้างคลาส (Creating Classes) ใน Python

คำสั่ง class สร้างการกำหนดคลาสใหม่ ชื่อของคลาสจะตามคีย์เวิร์ด class ทันที ตามด้วย colon ดังนี้:

class ClassName:
    'Optional class documentation string'
    class_suite
  • คลาสมี documentation string ซึ่งเข้าถึงได้ผ่าน ClassName.__doc__
  • class_suite ประกอบด้วยคำสั่งส่วนประกอบทั้งหมดที่กำหนดสมาชิกคลาส แอตทริบิวต์ข้อมูล และฟังก์ชัน

ตัวอย่าง

ตัวอย่างต่อไปนี้เป็นตัวอย่างของคลาส Python เรียบง่าย:

class Employee:
    'Common base class for all employees'
    empCount = 0
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
        Employee.empCount += 1
    def displayCount(self):
        print "Total Employee %d" % Employee.empCount
    def displayEmployee(self):
        print "Name : ", self.name, ", Salary: ", self.salary
  • ตัวแปร empCount เป็น class variable ซึ่งค่าถูกแบ่งปันระหว่างทุกอินสแตนซ์ของคลาสนี้ สามารถเข้าถึงได้เป็น Employee.empCount จากภายในหรือภายนอกคลาส
  • เมธอดแรก __init__ เป็นเมธอดพิเศษ เรียกว่า class constructor หรือ initialization method ที่ Python เรียกเมื่อคุณสร้างอินสแตนซ์ใหม่ของคลาสนี้
  • คุณประกาศเมธอดคลาสอื่นๆ เหมือนฟังก์ชันทั่วไป ยกเว้นว่า arguement แรกของแต่ละเมธอดคือ self Python เพิ่ม self argument ให้อัตโนมัติ คุณไม่ต้องรวมเมื่อเรียกเมธอด