Method Chaining là gì?
Kỹ thuật gọi nhiều phương thức trên cùng một object, chỉ dùng tham chiếu object một lần.
Ví dụ
class Foo:
def bar(self):
print("Foo.bar called")
return self # Quan trọng: trả về self
def baz(self):
print("Foo.baz called")
return self
foo = Foo()
# Không dùng chaining
foo.bar()
foo.baz()
# Dùng chaining
foo.bar().baz()
Kết quả
Foo.bar called Foo.baz called
Yêu cầu: Mỗi method trong chuỗi phải return self (hoặc object phù hợp).
Ứng dụng thực tế
- Builder pattern
- Fluent interface (ví dụ:
query.filter().order_by().limit()) - Cấu hình object:
config.set_a(1).set_b(2).build()