成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

編寫優雅代碼的八個內置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

在上述實現中,BUSMOTORCYCLE有相同的值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,它接受兩個參數baseexponent,并返回指數次冪基數的結果。我們使用原始函數創建了一個名為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()。我們添加了兩個數字45,結果是9,沒有創建類的任何實例。同樣,將83兩個數字相減得到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


責任編輯:華軒 來源: 51CTO
相關推薦

2022-06-17 09:08:27

代碼Python內置庫

2024-09-12 15:32:35

裝飾器Python

2024-09-23 09:00:00

裝飾器函數代碼

2022-09-21 13:32:39

Python裝飾器

2016-09-19 15:15:01

shellbash腳本

2022-03-18 21:27:36

Python無代碼

2024-05-21 10:40:09

開發前端裝飾器

2025-02-17 08:50:00

CSS代碼JavaScript

2024-03-27 14:06:58

Python代碼開發

2025-01-06 12:00:00

Python函數內置函數

2022-07-25 15:21:50

Java編程語言開發

2023-02-06 12:00:00

重構PythonPythonic

2025-04-03 08:27:00

Python代碼開發

2023-09-26 12:04:15

重構技巧Pythonic

2023-01-11 11:35:40

重構PythonPythonic

2018-10-08 08:42:06

編程語言DjangoPython

2024-12-30 07:47:15

Python科學計算

2022-12-01 16:53:27

NPM技巧

2022-09-14 08:16:48

裝飾器模式對象

2024-07-30 14:09:19

裝飾器Python代碼
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 亚洲成人精品一区二区 | 亚洲最大av | 亚洲欧美日韩国产综合 | 欧美性a视频 | 欧美视频三区 | 99九九久久 | 男女在线网站 | 99热热99| 久久精品网 | 久久久久国产一区二区三区四区 | 天天爽综合网 | 在线精品一区二区 | 亚洲综合一区二区三区 | 一区视频在线免费观看 | 中文字幕日韩欧美一区二区三区 | 亚洲综合在线网 | 亚洲三区在线 | 天堂av中文在线 | 成人免费视频网站在线看 | 欧美精品网站 | 久久精品国产99国产精品 | 久久福利电影 | 欧美日韩在线免费 | 欧美一区二区免费在线 | 亚洲人成人一区二区在线观看 | 人人操日日干 | 免费小视频在线观看 | 久热久热 | 亚洲小视频 | 国内自拍偷拍一区 | 国产欧美日韩久久久 | 亚洲国产精品99久久久久久久久 | www.蜜桃av.com| 亚洲一区二区在线播放 | 国产激情网站 | 中文字幕一区二区三区四区 | 久久最新精品视频 | 999精品视频在线观看 | 免费在线观看一级毛片 | 日本免费一区二区三区四区 | 国产精品久久久久久久久大全 |