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

อธิบาย Method Chaining ในคลาส Python

Method Chaining คืออะไร

Method Chaining เป็นเทคนิคเรียกเมธอดหลายตัวติดต่อกันบนออบเจ็กต์เดียว โดยใช้การอ้างอิงออบเจ็กต์เพียงครั้งเดียว

ตัวอย่าง

สมมติมีคลาส Foo ที่มีเมธอด bar และ baz

foo = Foo()

ไม่ใช้ Method Chaining:

foo.bar()
foo.baz()

ใช้ Method Chaining:

foo.bar().baz()

การนำไปใช้งานง่ายๆ

class Foo(object):
    def bar(self):
        print("Foo.bar called")
        return self
    def baz(self):
        print("Foo.baz called")
        return self

foo = Foo()
foo2 = foo.bar().baz()
print("id(foo):", id(foo))
print("id(foo2):", id(foo2))

ผลลัพธ์

Foo.bar called
Foo.baz called
id(foo): 87108128
id(foo2): 87108128

สังเกตว่า id(foo) และ id(foo2) เหมือนกัน เพราะแต่ละเมธอดคืน self กลับไป