Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!

Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount

เดกอเรเตอร์


Decorators ช่วยให้คุณสามารถแก้ไขวัตถุที่เรียกใช้งานได้ เช่น functions, methods, or classes ได้โดยง่าย ในบทเรียนนี้เราจะจัดการกับ functions สำหรับไวยากรณ์

เท่ากับว่า:

ตามที่คุณเห็น, decorator ก็คือฟังก์ชันอีกตัวหนึ่งที่รับฟังก์ชันแล้วส่งคืนหนึ่งฟังก์ชัน ตัวอย่างเช่น คุณสามารถทำเช่นนี้:

นี่จะทำให้ฟังก์ชันทำซ้ำสองครั้ง

คุณยังสามารถให้มันเปลี่ยนผลลัพธ์ได้

เปลี่ยน input

และทำการตรวจสอบ

สมมุติว่าคุณต้องการคูณผลลัพธ์ด้วยค่าตัวแปร คุณสามารถกำหนด decorator และใช้งานดังนี้:

คุณสามารถทำอะไรก็ได้ที่คุณต้องการกับฟังก์ชั่นเก่า แม้กระทั่งละเลยอย่างสิ้นเชิง! Decorator ระดับสูงยังสามารถจัดการกับ doc string และจำนวนอาร์กิวเมนต์ได้อีกด้วย สำหรับ decorators ที่น่าสนใจ ดูที่ http://wiki.python.org/moin/PythonDecoratorLibrary.

Exercise

สร้างโรงงาน decorator ที่ส่งคืน decorator ที่ตกแต่งฟังก์ชันที่มีอาร์กิวเมนต์เดียว โรงงานควรรับอาร์กิวเมนต์หนึ่งตัว, เป็น type, จากนั้นส่งคืน decorator ที่ทำให้ฟังก์ชันควรตรวจสอบว่าข้อความ input เป็น type ที่ถูกต้องหรือไม่ ถ้าไม่ถูกควรพิมพ์ว่า "Bad Type" (ในความเป็นจริง ควรจะให้เกิดข้อผิดพลาด แต่การแจ้งข้อผิดพลาดไม่อยู่ในบทเรียนนี้) ดูที่โค้ดในบทเรียนและผลลัพธ์ที่คาดหวังเพื่อดูว่ามันคืออะไรถ้าคุณสับสน (ฉันเข้าใจดีว่าฉันก็จะสับสน) การใช้ isinstance(object, type_of_object) หรือ type(object) อาจช่วยได้.

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

Previous Tutorial Next Tutorial Take the Test
Copyright © learnpython.org. Read our Terms of Use and Privacy Policy