วิธีเขียน Python แบบ Object Oriented

จริง ๆ แล้ว หลาย ๆ คนอาจจะได้ยินมาว่า python เป็นภาษา OO อีกภาษาหนึ่ง ซึ่งก็จริงครับ เพราะจะว่าไปแทบทุกภาษาเขียนแบบ OO ได้ แต่ python มีความ OO ที่เขียนได้สั้น เพราะเป็นภาษา script แบบนึง เราจะมาลองดูหน้าตากัน

  1. #/usr/bin/env python
  2. #สร้าง class ชื่อ MyBank
  3. #ระวังนิดนึงสำหรับมือใหม่ครับ python ใช้ tab ย่อหน้าเป็น token ในการเขียนโปรแกรมด้วย เพราะผมก็เจอ Error ตรงนี้ครับ
  4. class MyBank:# ย่อหน้าด้วย tab
  5.  
  6. def __init__(self):self.money = 0;
  7. print "This is init"
  8.  
  9. def deposit(self,money):
  10. self.money += money
  11. print "your money = " + str(self.money)
  12. def withdraw(self,money):
  13. self.money += money
  14. print "your money = "+ str(self.money)
  15. #สร้าง Object ของ class Mybank
  16. bank = MyBank()
  17.  
  18. #เรียกใช้งาน
  19. bank.deposit(1000)
  20. 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 ได้เพียงอันเดียวครับ ซึ่งจะใช้อันล่างสุดที่ประกาศ

  1. #/usr/bin/env python
  2. class MyBank:
  3. def __init__(self):
  4. print "This is init"
  5.  
  6. def __init__(self,deposit,withdraw):
  7. money = 0;
  8. money += deposit
  9. money -= withdraw
  10. print "your money = " + str(money)
  11.  

เมื่อสร้าง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

ใครมีข้อเสนอแนะนำมือใหม่อย่างผมก็ช่วยชี้แนะด้วยครับ


ความคิดเห็น

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

Google Friend Connect (leave a quick comment)
loading...
เนื้อหาของข้อมูลนี้ถูกรักษาเป็นความลับและไม่แสดงต่อสาธารณะ
CAPTCHA
คำถามนี้เป็นการทดสอบว่าท่านเป็น spam หรือไม่
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.