สัปดาห์นี่เราจะมาทำความรู้จักกับ Class และ Object กันครับ
.
.
.
เริ่มจากความหมายของ class กันก่อนเลยครับ
เริ่มจากความหมายของ class กันก่อนเลยครับ
Class คือเครื่องมือหรือเป็นตัวกำหนดส่วนประกอบต่างๆที่จะใช้ในการสร้าง Object โดยตัว Class แบ่งออกเป็น 2 ส่วนหลักๆคือ
- attributes คือ ตัวแปรของคลาสนั้นๆส่วนใหญ่จะเก็บไว้ใน Method __init__
- Method คือ ฟังก์ชันการทำงานที่กำหนดในแต่ละคลาส
การสร้าง Class ด้วย Python
class student: #สร้าง Student class
def __init__(self,name,Ids): #__init__ เป็น Constructor ถ้าใน C# หรือ java จะหมาย ถึง Method ที่ชื่อเดียวกันกับ class แต่ถ้าใน Python จะ เป็น Method ที่จะทำงานทุกครั้งที่เราส่งใช้งาน class หรือ object ที่ถูกสร้างจากคลาสนั้น
self.name = name # attributes ของ student class ทำหน้าที่เก็บชื่อ
self.Ids = Ids # attributes ของ student class ทำหน้าที่เก็บ Id ของนักศึกษา
def get_detail(self): #เป็น Method ที่ชื่อ get_detail เมื่อถูกสั่งใช้งาน
จะทำการแสดง ชื่อนักศึกษา และ Id ของนักศึกษา
print ('Name : ', self.name)
print ('ID student : ', self.Ids)
def __del__(self): #__del__ เป็น Destructor หรือ Method ที่จะทำงานเมื่อ เราทำการลบ Object ทิ้ง
print ('Good bye ',self.name) # เมื่อการลบ Object จะแสดง ข้อความ Good bye ตาม ด้วยชื่อนักศึกษาคนนั้น
K1=student('Kitsanapong',6101012630011) #สร้าง Object K1 โดยสร้างจาก student class
K1.get_detail() #ใช้ Method get_detail จาก student class
Output :
del K1 #ทำการลบ Object K1
Output :
def __init__(self,name,Ids): #__init__ เป็น Constructor ถ้าใน C# หรือ java จะหมาย ถึง Method ที่ชื่อเดียวกันกับ class แต่ถ้าใน Python จะ เป็น Method ที่จะทำงานทุกครั้งที่เราส่งใช้งาน class หรือ object ที่ถูกสร้างจากคลาสนั้น
self.name = name # attributes ของ student class ทำหน้าที่เก็บชื่อ
self.Ids = Ids # attributes ของ student class ทำหน้าที่เก็บ Id ของนักศึกษา
def get_detail(self): #เป็น Method ที่ชื่อ get_detail เมื่อถูกสั่งใช้งาน
จะทำการแสดง ชื่อนักศึกษา และ Id ของนักศึกษา
print ('Name : ', self.name)
print ('ID student : ', self.Ids)
def __del__(self): #__del__ เป็น Destructor หรือ Method ที่จะทำงานเมื่อ เราทำการลบ Object ทิ้ง
print ('Good bye ',self.name) # เมื่อการลบ Object จะแสดง ข้อความ Good bye ตาม ด้วยชื่อนักศึกษาคนนั้น
K1=student('Kitsanapong',6101012630011) #สร้าง Object K1 โดยสร้างจาก student class
K1.get_detail() #ใช้ Method get_detail จาก student class
Output :
del K1 #ทำการลบ Object K1
Output :
No comments:
Post a Comment