Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ฟังก์ชัน Python กับ Methods ของออบเจ็กต์ ตัวไหนพื้นฐานกว่า

ใน Python ฟังก์ชันเป็นออบเจ็กต์ที่เรียกได้ (callable) เรียกด้วย operator () ออบเจ็กต์อื่นๆ ก็สามารถเลียนแบบฟังก์ชันได้โดย implement __call__

Method เป็นฟังก์ชันพิเศษที่ผูกกับ instance (bound method) หรือไม่ผูก (unbound method)

ตัวอย่าง

def a(): pass
print(a)        # 
print(type(a))  # 

class C:
    def c(self): pass

print(C.c)          # 
print(type(C.c))    # 
print(C().c)        # >
print(type(C().c))  # 

Bound method ใช้เป็นฟังก์ชันได้โดยตรง นี่คือจุดแข็งของ Python: bound methods, functions, callable objects, class constructors ล้วนเรียกใช้รูปแบบเดียวกัน