วิธีเขียน Python แบบ Object Oriented
จริง ๆ แล้ว หลาย ๆ คนอาจจะได้ยินมาว่า python เป็นภาษา OO อีกภาษาหนึ่ง ซึ่งก็จริงครับ เพราะจะว่าไปแทบทุกภาษาเขียนแบบ OO ได้ แต่ python มีความ OO ที่เขียนได้สั้น เพราะเป็นภาษา script แบบนึง เราจะมาลองดูหน้าตากัน
#/usr/bin/env python #สร้าง class ชื่อ MyBank #ระวังนิดนึงสำหรับมือใหม่ครับ python ใช้ tab ย่อหน้าเป็น token ในการเขียนโปรแกรมด้วย เพราะผมก็เจอ Error ตรงนี้ครับ class MyBank:# ย่อหน้าด้วย tab def __init__(self):self.money = 0; print "This is init" def deposit(self,money): self.money += money print "your money = " + str(self.money) def withdraw(self,money): self.money += money print "your money = "+ str(self.money) #สร้าง Object ของ class Mybank bank = MyBank() #เรียกใช้งาน bank.deposit(1000) bank.deposit(500)
ผลลัพธ์ :
>>> This is init your money = 1000 your money = 1500
อธิบายโปรแกรม :
เราสร้าง class ชื่อ MyBank ใน python มี constructor ได้เพียงอันเดียวครับ คือ __init__(self) ซึ่งจะยกตัวอย่างต่อไป ทุก method ต้องมี self เพื่อให้สามารถ access attribute หรือ instance ของ class ได้ self.money เป็น instance ของ class self ก็ คล้าย ๆ กับ this ในภาษาจาวาครับ สังเกตว่า print "your money = " + str(self.money) ต้อง ทำ type casting จาก integer ไปเป็น string ก่อน ซึ่งเราไม่จำเป็นต้องประกาศชนิดก่อน ซึ่งต่างจาก php ที่เราสามารถเปลี่ยน type ได้เลยครับ python มี constructor ได้เพียงอันเดียวครับ ซึ่งจะใช้อันล่างสุดที่ประกาศ
#/usr/bin/env python class MyBank: def __init__(self): print "This is init" def __init__(self,deposit,withdraw): money = 0; money += deposit money -= withdraw print "your money = " + str(money)
เมื่อสร้างobject ด้วย bank = MyBank() จะเกิด error
>>> Traceback (most recent call last): File "C:/Documents and Settings/S@ke.EN39/Desktop/myoo2.py", line 23, in ? bank = MyBank() TypeError: __init__() takes exactly 3 arguments (1 given)
ต้องสร้างด้วย bank = MyBank(1000,500) ซึ่งมี 2 argument + self เป็น 3 ครับ ผลลัพธ์:
>>> your money = 500
ใครมีข้อเสนอแนะนำมือใหม่อย่างผมก็ช่วยชี้แนะด้วยครับ









ความคิดเห็น
แสดงความคิดเห็น