Devdit
 

Python ใช้ class ยังไง

785

Python ใช้ class ยังไง บทความนี้สอนการเรียกใช้งาน method ต่างๆ ที่อยู่ภายใน class โดยการใช้ class นั้นต้องเริ่มจากการสร้าง object หรือ instance จาก class ดังกล่าวก่อน และจึงเรียกใช้ method ที่ต้องการได้ สามารถเขียนโปรแกรมได้ดังนี้

 

ตัวอย่าง Python ใช้ class ยังไง

class Demo:
  def test1( self ):
    print("method test1")
  def test2( self ):
    print("method test2")

demo = Demo()
demo.test1()
demo.test2()

ผลลัพธ์

method test1
method test2

คำอธิบาย

Python ใช้ class จากตัวอย่างสร้าง object จาก class Demo ด้วย demo = Demo() และเรียกใช้งาน method test1 ด้วย demo.test1() และ method test2 ด้วย demo.test2() ภาษา Python

แก้ไข 1 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ