當前位置: 首頁>>AGI專欄>>正文


Python編程高級特性總結

Python 是一門功能強大且靈活的語言,提供了許多高級特性來簡化代碼、提高效率並增強功能。以下是一些 Python 中常用的高級特性:

1. 生成器(Generators)

生成器是一種特殊的迭代器,使用 yield 關鍵字來返回值。它不會一次性生成所有值,而是按需生成,節省內存。

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

# 使用生成器
fib = fibonacci()
for _ in range(10):
    print(next(fib))

2. 裝飾器(Decorators)

裝飾器是一種用於修改或擴展函數行為的工具。它本質上是一個高階函數,接受一個函數並返回另一個函數。

def my_decorator(func):
    def wrapper():
        print("Before function call")
        func()
        print("After function call")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()
  • 輸出:
    Copy
    Before function call
    Hello!
    After function call

3. 上下文管理器(Context Managers)

上下文管理器用於管理資源(如文件、數據庫連接等),確保資源在使用後被正確釋放。使用 with 語句實現。

# 使用 with 打開文件
with open("example.txt", "r") as file:
    content = file.read()
    print(content)
# 文件會在 with 塊結束後自動關閉
  • 自定義上下文管理器:
python
Copy
class MyContextManager:
    def __enter__(self):
        print("Entering the context")
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print("Exiting the context")

with MyContextManager() as cm:
    print("Inside the context")

4. 列表推導式(List Comprehensions)

列表推導式是一種簡潔的創建列表的方式。

# 生成平方數列表
squares = [x**2 for x in range(10)]
print(squares)
  • 帶條件的列表推導式:
python
Copy
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)

5. 集合和字典推導式(Set and Dictionary Comprehensions)

類似於列表推導式,集合和字典推導式可以快速生成集合和字典。

# 集合推導式
unique_squares = {x**2 for x in range(10)}
print(unique_squares)

# 字典推導式
square_dict = {x: x**2 for x in range(10)}
print(square_dict)

6. Lambda 函數

Lambda 函數是一種匿名函數,適合用於簡單的操作。

# 使用 lambda 排序
pairs = [(1, 'one'), (2, 'two'), (3, 'three')]
pairs.sort(key=lambda pair: pair[1])
print(pairs)

7. 函數式編程工具

Python 提供了 mapfilter 和 reduce 等函數式編程工具。

# map
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared)

# filter
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)

# reduce
from functools import reduce
sum_all = reduce(lambda x, y: x + y, numbers)
print(sum_all)

8. 動態類型和鴨子類型

Python 是動態類型語言,變量類型在運行時確定。鴨子類型(Duck Typing)意味著隻要對象具有所需的方法或屬性,就可以使用它。

class Duck:
    def quack(self):
        print("Quack!")

class Person:
    def quack(self):
        print("I'm quacking like a duck!")

def make_it_quack(thing):
    thing.quack()

make_it_quack(Duck())
make_it_quack(Person())

9. 元類(Metaclasses)

元類是類的類,用於控製類的創建行為。它是 Python 中非常高級的特性。

class Meta(type):
    def __new__(cls, name, bases, dct):
        print(f"Creating class {name}")
        return super().__new__(cls, name, bases, dct)

class MyClass(metaclass=Meta):
    pass

# 輸出:Creating class MyClass

10. 異步編程(Asynchronous Programming)

Python 的 asyncio 模塊支持異步編程,適合處理 I/O 密集型任務。

import asyncio

async def say_hello():
    print("Hello")
    await asyncio.sleep(1)
    print("World")

async def main():
    await asyncio.gather(say_hello(), say_hello())

asyncio.run(main())

11. 類型注解(Type Annotations)

Python 3.5+ 支持類型注解,可以提高代碼的可讀性和可維護性。

def greet(name: str) -> str:
    return f"Hello, {name}"

print(greet("Alice"))

12. 數據類(Data Classes)

Python 3.7+ 引入了 dataclass,用於快速創建存儲數據的類。

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

p = Point(10, 20)
print(p)

13. 枚舉(Enums)

枚舉是一種定義常量的方式,可以提高代碼的可讀性。

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

print(Color.RED)

14. 協程(Coroutines)

協程是一種輕量級的線程,可以在函數執行過程中暫停和恢複。

def coroutine():
    while True:
        value = yield
        print(f"Received: {value}")

c = coroutine()
next(c)  # 啟動協程
c.send(10)
c.send(20)

總結

Python 的高級特性包括生成器、裝飾器、上下文管理器、推導式、Lambda 函數、函數式編程工具、動態類型、元類、異步編程、類型注解、數據類、枚舉和協程等。掌握這些特性可以讓你編寫更高效、簡潔和強大的 Python 代碼。

本文由《純淨天空》出品。文章地址: https://vimsky.com/zh-tw/article/4806.html,轉載請注明來源鏈接。