Devdit
 

method กับ function ต่างกันอย่างไร

1.4K

method กับ function ต่างกันอย่างไร ทั้ง 2 เหมือนกัน ต่างกันตรงที่ method จะอยู่ใน class หรือการเขียนโปรแกรมเชิงวัตถุ ส่วน function สามารถสร้างที่ไหนของโค้ดก็ได้ ไม่ใช้แค่ใน class สามารถเขียนโปรแกรมได้ดังนี้

 

ตัวอย่าง method กับ function ต่างกันอย่างไร

# method
class MyClass:
    def helloWithMethod(self):
        print("Hello, Method")

myClass = MyClass()
myClass.helloWithMethod()
# function
def helloFunction():
    print("Hello, Function")

helloFunction()

ผลลัพธ์

Hello, Method
Hello, Function

คำอธิบาย

method กับ function จากตัวอย่างด้วยภาษา Python มี method ชื่อ helloWithMethod อยู่ใน class MyClass และมี function ชื่อ helloFunction โดยปกติการจะเรียกใช้ method ภายใน class จำเป็นต้องสร้าง object จาก class ก่อน ส่วน function สามารถเรียกใช้งานได้เลย

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