นากกายกดปุ่มชื่อเมธอดบนแผงมิ้นต์ แล้วการ์ดออบเจ็กต์เรียงตัวเอง

Python operator.methodcaller: เรียกเมธอดเป็นคีย์เรียง/แมปโดยไม่เขียนแลมบ์ดา

น้องกายEngineering

เขียน lambda x: x.lower() หรือ lambda p: p.replace("-", "_") ซ้ำจนจำเจไหมครับ — operator.methodcaller สร้าง callable ที่เรียกเมธอดชื่อนั้นให้อัตโนมัติ

เหมาะกับ:

  • sorted(items, key=methodcaller("lower"))
  • map(methodcaller("strip"), lines)
  • ส่งอาร์กิวเมนต์ติดไปได้ เช่น methodcaller("split", ",", 1)
import unittest
from operator import methodcaller


class MethodCallerTests(unittest.TestCase):
    def test_sorted_casefold(self):
        words = ["Banana", "apple", "Cherry"]
        ordered = sorted(words, key=methodcaller("casefold"))
        self.assertEqual(ordered, ["apple", "Banana", "Cherry"])

    def test_with_args(self):
        split_once = methodcaller("split", "-", 1)
        self.assertEqual(split_once("a-b-c"), ["a", "b-c"])


if __name__ == "__main__":
    unittest.main()

Recap

  • แทนที่แลมบ์ดาเรียกเมธอดเดี่ยวด้วย methodcaller
  • ใช้คู่ sorted / map / filter เมื่อชื่อเมธอดคงที่
  • ถ้าต้องคำนวณซับซ้อน — ยังใช้ฟังก์ชันจริงอ่านง่ายกว่า