編寫優雅代碼的八個內置Python裝飾器
譯文譯者 | 布加迪
審校 | 重樓
Python具有語法清晰易讀的優點,是一種廣泛使用的高級編程語言。Python是為確保易用性而設計的,注重簡潔性和降低程序的維護成本。它隨帶一個廣泛的庫,減少了開發人員從頭開始編寫代碼的需要,并提高了開發人員的生產力。Python的一項有助于確保代碼優雅的強大特性是裝飾器(decorator)。
Python裝飾器的定義
在Python中,decorator是一個函數,允許您修改另一個函數的行為,而不改變其核心邏輯。它接受另一個函數作為參數,并返回功能得到擴展的函數。這樣一來,您就可以使用裝飾器為現有函數添加一些額外的邏輯,只需要幾行代碼就可以提高可重用性。我們在本文中將介紹8個內置的Python裝飾器,它們可以幫助您編寫更優雅、更易于維護的代碼。
1. @atexit.register
@atexit.register裝飾器用于注冊在程序結束時執行的函數。該函數可用于在程序即將退出時執行任何任務,無論是由于正常執行還是由于意外錯誤。
例子:
import atexit
# Register the exit_handler function
@atexit.register
def exit_handler():
print("Exiting the program. Cleanup tasks can be performed here.")
# Rest of the program
def main():
print("Inside the main function.")
# Your program logic goes here.
if __name__ == "__main__":
main()
輸出:
Inside the main function.
Exiting the program. Cleanup tasks can be performed here.
在上面的實現中,@atexit.register在函數定義上面提及。它將exit_handler()函數定義為退出函數。實際上,這意味著每當程序到達其終止點,無論是通過正常執行還是由于意外錯誤導致過早退出,都將調用exit_handler()函數。
2. @dataclasses.dataclass
@dataclasses.dataclass是一個功能強大的裝飾器,用于自動為“__init__”、“__repr__”等其他類生成常見的特殊方法。由于不需要編寫用于初始化和比較類的實例的樣板方法,它可以幫助您編寫更干凈、更簡潔的代碼。它還可以通過確保在整個代碼庫中一致地實現常見的特殊方法來幫助防止錯誤。
例子:
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
point = Point(x=3, y=2)
# Printing object
print(point)
# Checking for the equality of two objects
point1 = Point(x=1, y=2)
point2 = Point(x=1, y=2)
print(point1 == point2)
輸出:
Point(x=3, y=2)
True
@dataclass裝飾器應用于Point類定義之上,通知Python使用默認行為來生成特殊方法。這會自動創建__init__方法,該方法在對象實例化時初始化類屬性,比如x和y。因此,可以在不需要顯式編碼的情況下構造像point這樣的實例。此外,負責提供對象字符串表示的__repr__方法也會自動加以調整。這確保了在打印輸出對象(比如point)時,它會生成清晰而有序的表示,比如輸出:point (x=3, y=2)中所示。
此外,兩個實例point1和point2之間的相等性比較(==)生成True。這值得注意,因為默認情況下,Python根據內存位置來檢查是否相等。然而,在數據類對象上下文中,相等性取決于其中含有的數據。這是由于@dataclass裝飾器生成了一個__eq__方法,該方法檢查對象中存在的數據是否相等,而不是檢查相同的內存位置。
3. @enum.unique
@enum.unique裝飾器位于enum模塊中,用于確保枚舉中所有成員的值是唯一的。這有助于防止意外創建具有相同值的多個枚舉成員,不然會導致混淆和錯誤。如果發現重復的值,拋出ValueError(值錯誤)。
例子:
from enum import Enum, unique
@unique
class VehicleType(Enum):
CAR = 1
TRUCK = 2
MOTORCYCLE = 3
BUS = 4
# Attempting to create an enumeration with a duplicate value will raise a ValueError
try:
@unique
class DuplicateVehicleType(Enum):
CAR = 1
TRUCK = 2
MOTORCYCLE = 3
# BUS and MOTORCYCLE have duplicate values
BUS = 3
except ValueError as e:
print(f"Error: {e}")
輸出:
Error: duplicate values found in : BUS -> MOTORCYCLE
在上述實現中,“BUS”和“MOTORCYCLE”有相同的值“3”。因此,@unique裝飾器拋出值錯誤,顯示一條消息,表明發現了重復的值。您既不能多次使用相同的鍵,也不能將相同的值分配給不同的成員。通過這種方式,它有助于防止多個枚舉成員出現重復值。
4. @partial
partial裝飾器是一個強大的工具,用于創建偏函數。偏函數允許您預先設置一些原始函數的參數,然后用已經填寫的這些參數生成一個新的函數。
例子:
from functools import partial
# Original function
def power(base, exponent):
return base ** exponent
# Creating a partial function with the exponent fixed to 2
square = partial(power, expnotallow=2)
# Using the partial function
result = square(3)
print("Output:",result)
輸出:
Output: 9
在上面的實現中,我們有一個函數“power”,它接受兩個參數“base”和“exponent”,并返回指數次冪基數的結果。我們使用原始函數創建了一個名為“square”的偏函數,其中指數被預先設置為2。這樣一來,我們可以使用partial裝飾器擴展原始函數的功能。
5. @singledispatch
@singledisptach裝飾器用于創建泛型函數。它允許您定義名稱相同但參數類型各異的函數的不同實現。當您希望代碼針對不同的數據類型有不同的行為時,這個裝飾器就特別有用。
例子:
from functools import singledispatch
# Decorator
@singledispatch
def display_info(arg):
print(f"Generic: {arg}")
# Registering specialized implementations for different types
@display_info.register(int)
def display_int(arg):
print(f"Received an integer: {arg}")
@display_info.register(float)
def display_float(arg):
print(f"Received a float: {arg}")
@display_info.register(str)
def display_str(arg):
print(f"Received a string: {arg}")
@display_info.register(list)
def display_sequence(arg):
print(f"Received a sequence: {arg}")
# Using the generic function with different types
display_info(39)
display_info(3.19)
display_info("Hello World!")
display_info([2, 4, 6])
輸出:
Received an integer: 39
Received a float: 3.19
Received a string: Hello World!
Received a sequence: [2, 4, 6]
在上面的實現中,我們先使用@singledisptach裝飾器開發了泛型函數display_info(),然后分別為整數、浮點、字符串和列表注冊了其實現。輸出顯示了display_info()針對不同數據類型的工作機理。
6. @classmethod
@classmethod是一個裝飾器,用于在類中定義類方法。類方法綁定到類而不是綁定到類的對象。靜態方法與類方法的主要區別在于它們與類狀態的交互。類方法可以訪問并修改類狀態,而靜態方法無法訪問類狀態、獨立操作。
例子:
class Student:
total_students = 0
def __init__(self, name, age):
self.name = name
self.age = age
Student.total_students += 1
@classmethod
def increment_total_students(cls):
cls.total_students += 1
print(f"Class method called. Total students now: {cls.total_students}")
# Creating instances of the class
student1 = Student(name="Tom", age=20)
student2 = Student(name="Cruise", age=22)
# Calling the class method
Student.increment_total_students() #Total students now: 3
# Accessing the class variable
print(f"Total students from student 1: {student1.total_students}")
print(f"Total students from student 2: {student2.total_students}")
輸出:
Class method called. Total students now: 3
Total students from student 1: 3
Total students from student 2: 3
在上面的實現中,Student類擁有total_students這個類變量。@classmethod裝飾器用于定義increment_total_students()類方法,以增加total_students變量。每當我們創建Student類的實例時,學生總數就增加1。我們創建了這個類的兩個實例,然后使用類方法將total_students變量修改為3,這個類的實例也反映了這點。
7. @staticmethod
@staticmethod裝飾器用于在類中定義靜態方法。靜態方法是無需創建類實例即可調用的方法。靜態方法常常用于不需要訪問與對象相關的參數,與整個類更加相關。
例子:
class MathOperations:
@staticmethod
def add(x, y):
return x + y
@staticmethod
def subtract(x, y):
return x - y
# Using the static methods without creating an instance of the class
sum_result = MathOperations.add(5, 4)
difference_result = MathOperations.subtract(8, 3)
print("Sum:", sum_result)
print("Difference:", difference_result)
輸出:
Sum: 9
Difference: 5
在上面的實現中,我們使用@staticmethod為類“MathOperations”定義了一個靜態方法add()。我們添加了兩個數字“4”和“5”,結果是“9”,沒有創建類的任何實例。同樣,將“8”和“3”兩個數字相減得到“5”。這樣一來,就可以生成靜態方法,以執行不需要實例狀態的效用函數。
8. @ property
@property裝飾器用于定義類屬性的getter方法。getter方法是返回屬性值的方法。這種方法用于數據封裝,指定誰可以訪問類或實例的詳細信息。
例子:
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
# Getter method for the radius.
return self._radius
@property
def area(self):
# Getter method for the area.
return 3.14 * self._radius**2
# Creating an instance of the Circle class
my_circle = Circle(radius=5)
# Accessing properties using the @property decorator
print("Radius:", my_circle.radius)
print("Area:", my_circle.area)
輸出:
Radius: 5
Area: 78.5
在上面的實現中,類“Circle”有一個屬性“radius”。我們使用@property為半徑和面積設置了getter方法。它為類的用戶提供了一個干凈一致的接口來訪問這些屬性。
結語
本文重點介紹了一些最通用和最實用的裝飾器,您可以使用它們提高代碼的靈活性和可讀性。這些修飾器讓您可以擴展原始函數的功能,使原始函數更富條理性,更不容易出錯。它們如同神奇的魔法棒,使您的Python程序看起來整潔、運行起來順暢。
原文標題:8 Built-in Python Decorators to Write Elegant Code,作者:Kanwal Mehreen
鏈接:https://www.kdnuggets.com/8-built-in-python-decorators-to-write-elegant-code