亞洲資本網(wǎng) > 資訊 > 焦點(diǎn) > 正文
理解 10 個(gè)最難的 Python 概念
2023-08-28 18:22:32來源: 啟辰8


Python語法簡單,易于學(xué)習(xí),是初學(xué)者的理想選擇。 然而,當(dāng)您深入研究 Python 時(shí),您可能會(huì)遇到一些難以理解的具有挑戰(zhàn)性的概念。


(資料圖片)

在本文中,我將解釋 10 個(gè)最難的 Python 概念,包括遞歸、生成器、裝飾器、面向?qū)ο缶幊?、線程、異常處理、*args 和 **kwargs、函數(shù)式編程、推導(dǎo)式和集合。

1. 遞歸

遞歸是一種編程技術(shù),其中函數(shù)重復(fù)調(diào)用自身,直到滿足特定條件。 在 Python 中,遞歸函數(shù)是在自己的代碼塊中調(diào)用自身的函數(shù)。

以下是 Python 中計(jì)算數(shù)字階乘的遞歸函數(shù)的示例:

def factorial(n):    if n == 0:        return 1    else:        return n * factorial(n-1)

在此示例中,函數(shù) Factorial() 接受參數(shù) n 并檢查它是否等于 0。 如果 n 為零,則返回 1,因?yàn)?0 的階乘為 1。如果 n 不為零,則使用參數(shù) n-1 調(diào)用自身,并將結(jié)果與 n 相乘。 這一直持續(xù)到 n 變?yōu)?0 并且函數(shù)返回最終結(jié)果。



2. 生成器

生成器是產(chǎn)生一系列結(jié)果的函數(shù),但不創(chuàng)建列表。 它們比列表更節(jié)省內(nèi)存。

具體來說,生成器是使用一種稱為生成器函數(shù)的特殊函數(shù)創(chuàng)建的。 這些函數(shù)的定義與常規(guī)函數(shù)類似,但它們不返回值,而是使用“yield”關(guān)鍵字返回生成器對象。 然后,可以在循環(huán)中使用生成器對象,根據(jù)需要一次生成一個(gè)值。

def my_generator():    for i in range(10):        yield ifor num in my_generator():    print(num)# Output# 0# 1# 2# 3# 4# 5# 6# 7# 8# 9

在此示例中,my_generator 函數(shù)生成從 0 到 9 的數(shù)字序列。調(diào)用該函數(shù)時(shí),它返回一個(gè)生成器對象,可用于迭代序列的值。


3. 裝飾器

裝飾器是修改其他函數(shù)行為的函數(shù)。 裝飾器最常見的用途之一是在不修改原始代碼的情況下向現(xiàn)有函數(shù)添加功能。

在 Python 中,裝飾器是將另一個(gè)函數(shù)作為參數(shù)、修改它并返回它的函數(shù)。 它們用“@”符號編寫,后跟裝飾器函數(shù)的名稱。

def my_decorator(func):    def wrapper():        print("Before the function is called.")        func()        print("After the function is called.")    return wrapper@my_decoratordef say_hello():    print("Hello World!")# Call the decorated functionsay_hello()# Output:# Before the function is called.# Hello World!# After the function is called.

在此示例中,my_decorator 是一個(gè)裝飾器函數(shù),它將函數(shù)作為其參數(shù)并返回一個(gè)新的函數(shù)包裝器。 包裝函數(shù)在調(diào)用原始函數(shù)之前和之后添加了一些額外的功能。

@my_decorator 語法是將 my_decorator 函數(shù)應(yīng)用于 say_hello 函數(shù)的簡寫方式。 當(dāng)say_hello被調(diào)用時(shí),實(shí)際上是調(diào)用my_decorator返回的包裝函數(shù),而my_decorator又調(diào)用了原來的say_hello函數(shù)。 這允許我們向 say_hello 函數(shù)添加額外的行為,而無需直接修改其代碼。

4. 面向?qū)ο缶幊?/h1>

Python 是一種面向?qū)ο缶幊蹋∣OP)語言。 OOP 是一種編程范式,強(qiáng)調(diào)使用對象和類來組織和構(gòu)造代碼。

OOP 是通過使用類創(chuàng)建可重用代碼來創(chuàng)建可重用代碼。 對象本質(zhì)上是類的實(shí)例,并且配備有定義其行為的屬性(數(shù)據(jù))和方法(函數(shù))。

要在 Python 中創(chuàng)建類,請使用 class 關(guān)鍵字,后跟類的名稱和冒號。 在類內(nèi)部,您可以使用函數(shù)定義其屬性和方法。

例如,假設(shè)我們要?jiǎng)?chuàng)建一個(gè)名為 Person 的類,它具有 name 屬性和打印問候消息的greet 方法。 我們可以這樣定義它:

class Person:    def __init__(self, name):        self.name = name
def greet(self):        print("Hello, my name is", self.name)# Create a new Person object with the name Johnperson = Person("John")print(person.name) # Johnperson.greet() # Hello, my name is John

5. 線程

線程是一種用于同時(shí)執(zhí)行多個(gè)線程的技術(shù)。 它可以顯著提高程序的性能。 這是一個(gè)例子:

import threadingdef print_numbers():    for i in range(1, 11):        print(i)def print_letters():    for letter in ["a", "b", "c", "d", "e"]:        print(letter)thread1 = threading.Thread(target=print_numbers)thread2 = threading.Thread(target=print_letters)thread1.start()thread2.start()thread1.join()thread2.join()print("Finished")

在此示例中,我們定義了兩個(gè)函數(shù) print_numbers 和 print_letters,它們分別簡單地將一些數(shù)字和字母打印到控制臺(tái)。 然后,我們創(chuàng)建兩個(gè) Thread 對象,將目標(biāo)函數(shù)作為參數(shù)傳遞,并使用 start() 方法啟動(dòng)它們。 最后,我們使用 join() 方法等待兩個(gè)線程完成,然后再將“Finished”打印到控制臺(tái)。

6. 異常處理

異常處理是處理程序在執(zhí)行過程中可能出現(xiàn)的運(yùn)行時(shí)錯(cuò)誤或異常的過程。 Python提供了一種機(jī)制來捕獲和處理程序執(zhí)行過程中出現(xiàn)的異常,保證程序即使出現(xiàn)錯(cuò)誤也能繼續(xù)運(yùn)行。

try:    numerator = int(input("Enter numerator: "))    denominator = int(input("Enter denominator: "))    result = numerator / denominator    print("Result: ", result)except ZeroDivisionError:    print("Error: Cannot divide by zero!")except ValueError:    print("Error: Invalid input. Please enter an integer.")except Exception as e:    print("An error occurred:", e)

在此示例中,try 塊包含可能引發(fā)異常的代碼。 如果引發(fā)異常,它將被相應(yīng)的 except 塊捕獲。

通過使用異常處理,我們可以處理代碼中的錯(cuò)誤并防止程序崩潰。 它向用戶提供反饋,并根據(jù)發(fā)生的錯(cuò)誤類型采取適當(dāng)?shù)牟僮鳌?/span>



7. *args 和 **kwargs

在 Python 中,*args 和 **kwargs 用于將未指定數(shù)量的參數(shù)傳遞給函數(shù)。 因此,在編寫函數(shù)定義時(shí),您不必知道將向函數(shù)傳遞多少個(gè)參數(shù)。

*args 用于將可變數(shù)量的非關(guān)鍵字參數(shù)傳遞給函數(shù)。 * 運(yùn)算符用于將傳遞給函數(shù)的參數(shù)解包到元組中。 這允許您將任意數(shù)量的參數(shù)傳遞給函數(shù)。

def my_function(*args):    for arg in args:        print(arg)my_function("hello", "world", "!")# Output:# hello# world# !

**kwargs 用于將可變數(shù)量的關(guān)鍵字參數(shù)傳遞給函數(shù)。 ** 運(yùn)算符用于將傳遞給函數(shù)的關(guān)鍵字參數(shù)解壓縮到字典中。 這允許您將任意數(shù)量的關(guān)鍵字參數(shù)傳遞給函數(shù)。

def my_function(**kwargs):    for key, value in kwargs.items():        print(key, value)my_function(name="John", age=30, city="New York")# Output:# name John# age 30# city New York

8.函數(shù)式編程

函數(shù)式編程是一種強(qiáng)調(diào)使用函數(shù)來解決問題的編程范式。 Python 通過多個(gè)內(nèi)置函數(shù)和特性(包括 lambda 函數(shù)、map()、filter() 和 reduce())提供對函數(shù)式編程的支持。

Lambda 是單行函數(shù)。

# A lambda function to square a numbersquare = lambda x: x**2# Using the lambda functionprint(square(5))   # Output: 25

map() 將函數(shù)應(yīng)用于可迭代對象的每個(gè)元素,并返回一個(gè)包含結(jié)果的新可迭代對象。

nums = [1, 2, 3, 4, 5]squared_nums = list(map(lambda x: x**2, nums))print(squared_nums) # Output: [1, 4, 9, 16, 25]

filter() 創(chuàng)建一個(gè)函數(shù)返回 true 的元素列表。

nums = [1, 2, 3, 4, 5]even_nums = list(filter(lambda x: x % 2 == 0, nums))print(even_nums) # Output: [2, 4]

reduce() 以累積方式將函數(shù)應(yīng)用于可迭代的元素并返回單個(gè)值。

from functools import reducenums = [1, 2, 3, 4, 5]product = reduce(lambda x, y: x*y, nums)print(product) # Output: 120


9. 推導(dǎo)式

在 Python 中,推導(dǎo)式是一種簡潔高效的方法,通過對可迭代對象的元素應(yīng)用轉(zhuǎn)換或過濾條件來創(chuàng)建新列表、字典或集合。

列表推導(dǎo)式:

# Create a list of squares for the first 10 positive integerssquares = [x**2 for x in range(1, 11)]print(squares)# Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

字典:

# Create a dictionary with keys from a list and values as the length of each keyfruits = ["apple", "banana", "kiwi", "mango"]fruit_lengths = {fruit: len(fruit) for fruit in fruits}print(fruit_lengths)# Output: {"apple": 5, "banana": 6, "kiwi": 4, "mango": 5}

Set 推導(dǎo)式:

# Create a set of all even numbers between 1 and 20evens = {x for x in range(1, 21) if x % 2 == 0}print(evens)# Output: {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}

生成器推導(dǎo)式:

# Create a generator that yields the square of each number from 1 to 10squares_gen = (x**2 for x in range(1, 11))for square in squares_gen:    print(square)# Output:# 1# 4# 9# 16# 25# 36# 49# 64# 81# 100



10. 集合

在 Python 中,集合模塊提供了內(nèi)置類型的替代方案,這些替代方案更高效并提供附加功能,例如計(jì)數(shù)器、默認(rèn)字典和命名元組。

集合模塊中的 Counter 類用于計(jì)算列表中元素的出現(xiàn)次數(shù)。

from collections import Counterlst = ["apple", "banana", "cherry", "apple", "cherry", "cherry"]count = Counter(lst)print(count)# Output: Counter({"cherry": 3, "apple": 2, "banana": 1})print(count["cherry"])# Output: 3

Defaultdict 類是內(nèi)置 dict 類的子類,它為缺失的鍵提供默認(rèn)值。

from collections import defaultdictd = defaultdict(int)d["a"] = 1d["b"] = 2print(d["a"])# Output: 1print(d["c"])# Output: 0 (default value for missing keys is 0 because of int argument)

nametuple 類用于創(chuàng)建命名元組,它與常規(guī)元組類似,但字段被命名,從而更容易訪問它們。

from collections import namedtuplePerson = namedtuple("Person", ["name", "age", "gender"])p1 = Person(name="Alice", age=30, gender="Female")p2 = Person(name="Bob", age=25, gender="Male")print(p1.name)# Output: Aliceprint(p2.age)# Output: 25

感謝您的閱讀,我希望本文能夠幫助您更好地理解最具挑戰(zhàn)性的 Python 概念!

關(guān)鍵詞:

專題新聞
  • 10812名殘疾兒童獲得搶救性康復(fù)救助
  • 手機(jī)拍攝視頻技巧與拍攝方法教程 手機(jī)拍攝視頻技巧與拍攝方法
  • 菲利克斯·卡通戈(關(guān)于菲利克斯·卡通戈簡述)
  • 普門科技:2023年半年度凈利潤約1.35億元 同比增加35.19%
  • 9月8日火炬?zhèn)鬟f之日《榮耀亞運(yùn)》首發(fā)上市
  • 華為相機(jī)錯(cuò)誤無法啟動(dòng)相機(jī) 華為手機(jī)相機(jī)無法啟動(dòng)
最近更新

京ICP備2021034106號-51

Copyright © 2011-2020  亞洲資本網(wǎng)   All Rights Reserved. 聯(lián)系網(wǎng)站:55 16 53 8 @qq.com