国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁 後端開發(fā) Python教學(xué) 使用 ZeroMQ 在分散式系統(tǒng)中傳送訊息

使用 ZeroMQ 在分散式系統(tǒng)中傳送訊息

Nov 21, 2024 am 07:33 AM

使用 ZeroMQ 在分散式系統(tǒng)中傳送訊息

讓我們使用 Python 來發(fā)展不同的訊息傳遞模式。

您需要觀看以下影片才能按照逐步命令進(jìn)行操作。

慢慢來;確保在運(yùn)行命令之前仔細(xì)檢查它們。

  • 以下影片示範(fàn)了本教學(xué)中使用的指令。

Messaging in distributed systems using ZeroMQ

我在我的 GCP 虛擬機(jī)上運(yùn)行本教程,但也可以在本地運(yùn)行它 ?

本教學(xué)使用 ZeroMQ 介紹 Python3 中套接字的概念。 ZeroMQ 是一種開發(fā)套接字的簡單方法,允許分散式進(jìn)程透過發(fā)送訊息相互通訊。

  • 最簡單的形式是,一個套接字(節(jié)點(diǎn))「監(jiān)聽」特定的 IP 端口,同時另一個套接字伸出來形成連接。使用套接字,我們可以擁有一對一、一對多和多對多連線模式。

我們今天將研究的訊息傳遞模式如下:

  • 配對: 排他的、一對一的通信,兩個同伴相互通信。通訊是雙向的,套接字中沒有儲存特定的狀態(tài)。伺服器監(jiān)聽某個端口,客戶端連接到該端口。

Messaging in distributed systems using ZeroMQ

  • 客戶端 – 伺服器:客戶端連接到一臺或多臺伺服器。此模式允許請求-回應(yīng)模式。客戶端發(fā)送請求“zmq.REQ”並接收回應(yīng)。

Messaging in distributed systems using ZeroMQ

  • 發(fā)布/訂閱: 一種傳統(tǒng)的通訊模式,訊息的發(fā)送者(稱為發(fā)布者)將訊息傳送到特定的接收者(稱為訂閱者)。訊息的發(fā)布無需知道該知識的訂閱者是什麼或是否存在。多個訂閱者訂閱由發(fā)布者發(fā)布的消息/主題,或者一個訂閱者可以連接到多個發(fā)布者。

Messaging in distributed systems using ZeroMQ

  • 推拉套接字(又稱管道):讓您將訊息分發(fā)給排列在管道中的多個工作人員。 Push 套接字會將發(fā)送的訊息均勻分發(fā)到其 Pull 用戶端。這相當(dāng)於生產(chǎn)者/消費(fèi)者模型,但是消費(fèi)者計算的結(jié)果不會發(fā)送到上游,而是下游到另一個拉取/消費(fèi)者套接字。

Messaging in distributed systems using ZeroMQ

注意: 使用套接字可能會很棘手,使用相同的連接埠號碼/相同的套接字一次又一次運(yùn)行相同的程式碼,可能會導(dǎo)致連接「掛起」(伺服器看起來像是正在運(yùn)行,但它不能接受連接)。發(fā)生這種情況是因?yàn)槲覀儧]有正確關(guān)閉和銷毀之前的連接。

解決這個問題最合適的方法是關(guān)閉套接字並銷毀 ZeroMQ 上下文。有關(guān)更多詳細(xì)信息,請參閱第 2 階段和第 3 階段的 try – catch 區(qū)塊。

在本教學(xué)中,您可能會遇到此類問題,例如,在同一連接埠中多次執(zhí)行相同伺服器。如果您遇到掛起問題,建議您終止 Python 進(jìn)程,清理 TCP 連接埠號碼,然後再次執(zhí)行伺服器(請參閱步驟 11)。

第 1 階段:將伺服器與客戶端配對

讓我們先建立一個新的虛擬機(jī),然後我們將安裝Python3。

  • 保留虛擬機(jī)器內(nèi)部 IP 的副本,在本教學(xué)中我們將使用內(nèi)部 IP 位址。
    1. 開啟一個新的終端連接並執(zhí)行以下命令(一個接一個)。最後一個指令安裝 ZeroMQ。
$ sudo apt update
$ sudo apt install software-properties-common
$ sudo apt install python3.8
$ sudo apt-get -y install python3-pip
$ pip3 install pyzmq

出現(xiàn)提示時輸入:Y。

如今許多應(yīng)用程式都包含跨網(wǎng)路的元件,因此訊息傳遞至關(guān)重要。今天我們將使用 TCP 進(jìn)行訊息傳輸。

您可以使用 VSC 存取您的虛擬機(jī),也可以使用 SSH 執(zhí)行命令並使用 pico 編輯文件,在我的例子中,我將使用 SSH。

?確保仔細(xì)複製代碼。

我們需要建立第一個ZeroMQ 伺服器,該伺服器一次只允許與一個客戶端綁定。

  • 建立一個名為pair-server.py的新文件,然後輸入以下程式碼。

  • 程式碼使用 zmq.PAIR 模式建立一個新套接字,然後將伺服器綁定到特定的 IP 連接埠(我們已經(jīng)在 GCP 中開啟)。請注意,在我們停止伺服器之前,伺服器不會停止運(yùn)作。

  • 查看評論以了解其工作原理。

  • 確保更改 ;這是 GCP 虛擬機(jī)器的 內(nèi)部 IP 位址;用戶端連接埠應(yīng)與伺服器連接埠相同。

# import the library
import zmq
import time
# Initialize a new context that is the way to create a socket
context = zmq.Context()
# We will build a PAIR connection
socket = context.socket(zmq.PAIR) # We create a PAIR server
# Do not worry about this for the moment...
socket.setsockopt(zmq.LINGER, 0) 
# Create a new socket and "bind" it in the following address
# Make sure you update the address
socket.bind("tcp://<INTERNAL_VM_ADDRESS>:5555") # IP:PORT
# Keep the socket alive for ever...
while True:
    # Send a text message to the client (send_string)
    socket.send_string("Server message to Client")
    # Receive a message, store it in msg and then print it
    msg = socket.recv()
    print(msg)
    # Sleep for 1 second, so when we run it, we can see the results
    time.sleep(1)

先不要運(yùn)行伺服器,首先讓我們建立客戶端。

建立客戶端並花一點(diǎn)時間檢查評論。我將其命名為pair-client.py。

確保更改 ;連接埠應(yīng)與伺服器中的連接埠相同。

$ sudo apt update
$ sudo apt install software-properties-common
$ sudo apt install python3.8
$ sudo apt-get -y install python3-pip
$ pip3 install pyzmq

我們需要兩個個終端視窗來運(yùn)作PAIR範(fàn)例。我們將在一個視窗上運(yùn)行伺服器,在另一個視窗上運(yùn)行客戶端?,F(xiàn)在,按如下方式運(yùn)行它。

  • 運(yùn)行伺服器
# import the library
import zmq
import time
# Initialize a new context that is the way to create a socket
context = zmq.Context()
# We will build a PAIR connection
socket = context.socket(zmq.PAIR) # We create a PAIR server
# Do not worry about this for the moment...
socket.setsockopt(zmq.LINGER, 0) 
# Create a new socket and "bind" it in the following address
# Make sure you update the address
socket.bind("tcp://<INTERNAL_VM_ADDRESS>:5555") # IP:PORT
# Keep the socket alive for ever...
while True:
    # Send a text message to the client (send_string)
    socket.send_string("Server message to Client")
    # Receive a message, store it in msg and then print it
    msg = socket.recv()
    print(msg)
    # Sleep for 1 second, so when we run it, we can see the results
    time.sleep(1)
  • 運(yùn)行客戶端
import zmq
import time
# Same as before, initialize a socket
context = zmq.Context()
socket = context.socket(zmq.PAIR) # We create a PAIR server
socket.setsockopt(zmq.LINGER, 0)
# Connect to the IP that we already bind in the server
socket.connect("tcp://<INTERNAL_VM_ADDRESS>:5555")
# A counter will help us control our connection
# For example connect until you send 10 messages, then disconnect...
count = 0
while count<10:
    msg = socket.recv()
    print(msg)
    socket.send_string("Hello from Client")
    socket.send_string("This is a client message to server")
    print("Counter: ",count)
    count+=1
    time.sleep(1)
# Destroy the context socket and then close the connection
context.destroy()
socket.close()

檢查輸出,我們剛剛建立了一個新的 PAIR 套接字。

  • 當(dāng)客戶端完成連線時,腳本將終止。然後停止伺服器(ctrl c)並殺死它。

在再次運(yùn)行之前,我們需要清除 TCP 連線。為此,請使用以下命令。

$ python3 pair-server.py

?備註:

  • 我們一次只能運(yùn)行一個PAIR,這意味著我們不能有多個客戶端,記住這是一個PAIR,第一個客戶端將鎖定套接字.

  • 如果我們運(yùn)行伺服器一次,客戶端運(yùn)行兩次,第二個客戶端將“掛起”,這意味著第二個客戶端將等待新伺服器連線。

  • 如果我們想要多次運(yùn)行該對,我們需要終止伺服器並清除 TCP 連線。

  • PAIR 當(dāng)客戶端需要獨(dú)佔(zhàn)存取伺服器時是理想的選擇。

  • 我們可以將多個伺服器作為一對連接到多個客戶端,但我們需要使用不同的連接埠號碼進(jìn)行連接。

每個階段都是相互獨(dú)立的,因此,停止伺服器,清除 TCP 端口,然後進(jìn)入下一階段。

第 2 階段:將伺服器與多個客戶端配對

讓我們建立一個客戶端-伺服器連接,其中多個客戶端將連接到單一伺服器。這是最受歡迎的訊息傳遞模式。

  • 讓我們在 REP-REQ(回覆請求)模式的上下文中建立一個伺服器。
  • 我們將呼叫伺服器rep-server.py,使用連接埠5555。
$ python3 pair-client.py

現(xiàn)在我們將開發(fā)兩個功能相同的客戶端。

$ sudo fuser -k 5555/tcp # 5555 refers to your port number
import zmq
import time
try: # Try to create a new connection
    context = zmq.Context()
    socket = context.socket(zmq.REP) # We create a REP server
    # Here we set a linger period for the socket
    # Linger 0: no waiting period for new messages
    socket.setsockopt(zmq.LINGER, 0)
    socket.bind("tcp://<INTERNAL_VM_ADDRESS>:5555")
    while True: # Wait for next request from client
        message = socket.recv()
        print("Received request: ", message)
        time.sleep (1)  
        socket.send_string("Hi from Server")
except KeyboardInterrupt: # “ctr+c” to break and close the socket!
    context.destroy()
    socket.close()

讓我們建立該客戶端的副本並進(jìn)行對應(yīng)的編輯。執(zhí)行以下命令來製作新副本。

* **Client 1** will send a “Client 1 Hello world” request

* **Client 2** will send a “Client 2 Hello world” request to the server. 
* Let us create a file called `req-client1.py`, then edit as follows, again make sure you change the <INTERNAL_VM_ADDRESS>.

然後編輯req-client2.py並將客戶端1改為客戶端2。

讓我們編輯列印和套接字訊息(第 8 行和第 9 行)

import zmq
import time
context = zmq.Context()
socket = context.socket(zmq.REQ) # We create a REQ client (REQUEST)
socket.setsockopt(zmq.LINGER, 0)
socket.connect("tcp://<INTERNAL_VM_ADDRESS>:5555")
for request in range (1,10):
    print("Sending request Client 1 ", request,"...")
    socket.send_string("Hello from client 1")
    message = socket.recv()
    print("Received reply ", request, "[", message, "]")
socket.close()
context.destroy()

要執(zhí)行此範(fàn)例,我們需要三個 個終端窗口,一個用於伺服器,兩個用於客戶端。在第一個終端機(jī)中執(zhí)行以下命令。

  • 讓我們啟動伺服器
$ sudo apt update
$ sudo apt install software-properties-common
$ sudo apt install python3.8
$ sudo apt-get -y install python3-pip
$ pip3 install pyzmq
  • 讓我們啟動第一個客戶端
# import the library
import zmq
import time
# Initialize a new context that is the way to create a socket
context = zmq.Context()
# We will build a PAIR connection
socket = context.socket(zmq.PAIR) # We create a PAIR server
# Do not worry about this for the moment...
socket.setsockopt(zmq.LINGER, 0) 
# Create a new socket and "bind" it in the following address
# Make sure you update the address
socket.bind("tcp://<INTERNAL_VM_ADDRESS>:5555") # IP:PORT
# Keep the socket alive for ever...
while True:
    # Send a text message to the client (send_string)
    socket.send_string("Server message to Client")
    # Receive a message, store it in msg and then print it
    msg = socket.recv()
    print(msg)
    # Sleep for 1 second, so when we run it, we can see the results
    time.sleep(1)
  • 讓我們啟動第二個客戶端
import zmq
import time
# Same as before, initialize a socket
context = zmq.Context()
socket = context.socket(zmq.PAIR) # We create a PAIR server
socket.setsockopt(zmq.LINGER, 0)
# Connect to the IP that we already bind in the server
socket.connect("tcp://<INTERNAL_VM_ADDRESS>:5555")
# A counter will help us control our connection
# For example connect until you send 10 messages, then disconnect...
count = 0
while count<10:
    msg = socket.recv()
    print(msg)
    socket.send_string("Hello from Client")
    socket.send_string("This is a client message to server")
    print("Counter: ",count)
    count+=1
    time.sleep(1)
# Destroy the context socket and then close the connection
context.destroy()
socket.close()

檢查視窗的輸出,我們剛剛建立了兩個與一臺伺服器通訊的客戶端。您可以擁有任意數(shù)量的客戶端,您將需要建立客戶端,即使具有連接到一臺伺服器的不同功能。

? 備註:

  • 客戶端-伺服器是最廣泛使用的模式,當(dāng)我們安裝和執(zhí)行 Apache HTTP 伺服器時,我們已經(jīng)在第 1 類中使用了它。

  • 停止伺服器並清理 TCP 連接埠 5555

    • 殺死伺服器:


重?fù)?br> $ sudo fusion -k 5555/tcp

第 3 階段:將伺服器與客戶端配對

發(fā)布-訂閱模式是一種非常常見的方法,用於控制向訂閱上下文的許多客戶端廣播數(shù)據(jù),伺服器將數(shù)據(jù)發(fā)送到一個或多個客戶端。

$ python3 pair-server.py

讓我們先建立一個簡單的範(fàn)例。

$ python3 pair-client.py

讓我們建立一個新文件,命名為 pub_server.py。

$ sudo fuser -k 5555/tcp # 5555 refers to your port number
import zmq
import time
try: # Try to create a new connection
    context = zmq.Context()
    socket = context.socket(zmq.REP) # We create a REP server
    # Here we set a linger period for the socket
    # Linger 0: no waiting period for new messages
    socket.setsockopt(zmq.LINGER, 0)
    socket.bind("tcp://<INTERNAL_VM_ADDRESS>:5555")
    while True: # Wait for next request from client
        message = socket.recv()
        print("Received request: ", message)
        time.sleep (1)  
        socket.send_string("Hi from Server")
except KeyboardInterrupt: # “ctr+c” to break and close the socket!
    context.destroy()
    socket.close()
  • 該命令將指示 python 以特定的方式運(yùn)行伺服器
* **Client 1** will send a “Client 1 Hello world” request

* **Client 2** will send a “Client 2 Hello world” request to the server. 
* Let us create a file called `req-client1.py`, then edit as follows, again make sure you change the <INTERNAL_VM_ADDRESS>.

建立一個新檔案 pub_client.py。
* 此腳本接受來自命令列的三個參數(shù)(即 IP 和兩個連接埠)。

import zmq
import time
context = zmq.Context()
socket = context.socket(zmq.REQ) # We create a REQ client (REQUEST)
socket.setsockopt(zmq.LINGER, 0)
socket.connect("tcp://<INTERNAL_VM_ADDRESS>:5555")
for request in range (1,10):
    print("Sending request Client 1 ", request,"...")
    socket.send_string("Hello from client 1")
    message = socket.recv()
    print("Received reply ", request, "[", message, "]")
socket.close()
context.destroy()

我們已準(zhǔn)備好運(yùn)行我們的pub-sub應(yīng)用程式!我們需要三個個終端視窗。在第一個終端機(jī)中運(yùn)作:

$ cp req-client1.py req-client2.py
  • 在第二個終端機(jī)中運(yùn)作:
import zmq
import time
context = zmq.Context()
socket = context.socket(zmq.REQ) # We create a REQ client (REQUEST)
socket.setsockopt(zmq.LINGER, 0)
socket.connect("tcp://<INTERNAL_VM_ADDRESS>:5555")
for request in range (1,10):
    print("Sending request Client 2 ", request,"...")
        socket.send_string("Hello from client 2")
    message = socket.recv()
    print("Received reply ", request, "[", message, "]")
socket.close()
context.destroy()
  • 每個伺服器都會產(chǎn)生天氣資料。例如:
    • 郵遞區(qū)號,例如:10001
    • 溫帶,例如:-68

讓我們運(yùn)行客戶端以透過郵遞區(qū)號連接並訂閱數(shù)據(jù),例如 10001 (NYC)。請記住,客戶端腳本訂閱了兩個伺服器實(shí)例。執(zhí)行下一個指令:

$ python3 rep-server.py
  • 完成殺死伺服器(ctrl z)並清除 TCP 連接埠後,執(zhí)行以下命令:
$ python3 req-client1.py
$ python3 req-client2.py
第 4 階段:推/拉:使用管道模式**

推/拉套接字可讓您將訊息分發(fā)給排列在管道中的多個工作人員。這對於並行運(yùn)行程式碼非常有用。 Push 套接字會將訊息均勻分發(fā)到其 Pull 用戶端,客戶端將回應(yīng)傳送到另一個稱為收集器的伺服器。

Messaging in distributed systems using ZeroMQ

  • 這相當(dāng)於生產(chǎn)者/消費(fèi)者模型,但是消費(fèi)者計算的結(jié)果不會發(fā)送到上游,而是下游到另一個拉取/消費(fèi)者套接字。

  • 我們將實(shí)現(xiàn)以下功能。

  • 生產(chǎn)者將向消費(fèi)者推送 0 到 10 的隨機(jī)數(shù)。

  • 同一消費(fèi)者的兩個實(shí)例將拉取數(shù)字並執(zhí)行繁重的任務(wù)。

  • 任務(wù)可以是任何繁重的計算,例如矩陣乘法。

  • 為了簡單起見,我們的「繁重任務(wù)」將只傳回相同的數(shù)字。

  • 消費(fèi)者會將各個結(jié)果(繁重的任務(wù)計算)推送到結(jié)果收集器,該收集器將匯總結(jié)果。

  • 為了簡單起見,結(jié)果收集器的實(shí)例將拉取結(jié)果併計算每個消費(fèi)者的部分總和。如果需要,我們可以輕鬆地將兩個部分和加起來。

  • 讓我們來看一個簡單的例子。

    • 生產(chǎn)者生成 [1,2,3,4,5]。
    • 消費(fèi)者1接收到[2,4],然後計算一個繁重的任務(wù)並將結(jié)果轉(zhuǎn)發(fā)給結(jié)果收集器。
    • 消費(fèi)者2收到[1,3,5],然後計算一個繁重的任務(wù),並將結(jié)果轉(zhuǎn)發(fā)給結(jié)果收集器。
    • 結(jié)果收集器計算計數(shù)和部分總和,例如:
    • Consumer1[2,4],這表示從 Consumer1 收到 2 個數(shù)字,它們的總和為 6。
    • Consumer2[1,3,5],表示從該 Consumer2 收到 3 個數(shù)字,其總和為 9
  • 此範(fàn)例示範(fàn)了分散式處理並行處理的潛力。

首先,讓我們建立在連接埠 5555 上運(yùn)行的名為 Producer.py 的生產(chǎn)者,確保您調(diào)整了您的 .

$ sudo apt update
$ sudo apt install software-properties-common
$ sudo apt install python3.8
$ sudo apt-get -y install python3-pip
$ pip3 install pyzmq

然後建立consumer.py如下。不要忘記更改程式碼中的兩個 s。

# import the library
import zmq
import time
# Initialize a new context that is the way to create a socket
context = zmq.Context()
# We will build a PAIR connection
socket = context.socket(zmq.PAIR) # We create a PAIR server
# Do not worry about this for the moment...
socket.setsockopt(zmq.LINGER, 0) 
# Create a new socket and "bind" it in the following address
# Make sure you update the address
socket.bind("tcp://<INTERNAL_VM_ADDRESS>:5555") # IP:PORT
# Keep the socket alive for ever...
while True:
    # Send a text message to the client (send_string)
    socket.send_string("Server message to Client")
    # Receive a message, store it in msg and then print it
    msg = socket.recv()
    print(msg)
    # Sleep for 1 second, so when we run it, we can see the results
    time.sleep(1)

最後,讓我們開發(fā)collector.py,再改.

import zmq
import time
# Same as before, initialize a socket
context = zmq.Context()
socket = context.socket(zmq.PAIR) # We create a PAIR server
socket.setsockopt(zmq.LINGER, 0)
# Connect to the IP that we already bind in the server
socket.connect("tcp://<INTERNAL_VM_ADDRESS>:5555")
# A counter will help us control our connection
# For example connect until you send 10 messages, then disconnect...
count = 0
while count<10:
    msg = socket.recv()
    print(msg)
    socket.send_string("Hello from Client")
    socket.send_string("This is a client message to server")
    print("Counter: ",count)
    count+=1
    time.sleep(1)
# Destroy the context socket and then close the connection
context.destroy()
socket.close()

確保沒有縮排錯誤!

$ python3 pair-server.py

首先,我們需要運(yùn)行collector.py,收集器將等待資料被收集,直到我們啟動生產(chǎn)者。

$ python3 pair-client.py
  • 然後,我們將一一啟動消費(fèi)者,在不同的終端視窗中執(zhí)行每個命令。
$ sudo fuser -k 5555/tcp # 5555 refers to your port number
  • 在另一個終端機(jī)中執(zhí)行相同的命令。
import zmq
import time
try: # Try to create a new connection
    context = zmq.Context()
    socket = context.socket(zmq.REP) # We create a REP server
    # Here we set a linger period for the socket
    # Linger 0: no waiting period for new messages
    socket.setsockopt(zmq.LINGER, 0)
    socket.bind("tcp://<INTERNAL_VM_ADDRESS>:5555")
    while True: # Wait for next request from client
        message = socket.recv()
        print("Received request: ", message)
        time.sleep (1)  
        socket.send_string("Hi from Server")
except KeyboardInterrupt: # “ctr+c” to break and close the socket!
    context.destroy()
    socket.close()
  • 最後,我們將啟動生產(chǎn)者,開始將資料傳送到我們的管道。
* **Client 1** will send a “Client 1 Hello world” request

* **Client 2** will send a “Client 2 Hello world” request to the server. 
* Let us create a file called `req-client1.py`, then edit as follows, again make sure you change the <INTERNAL_VM_ADDRESS>.

幹得好! ?您使用 ZeroMQ 來開發(fā)訊息傳遞模式!

以上是使用 ZeroMQ 在分散式系統(tǒng)中傳送訊息的詳細(xì)內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強(qiáng)大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Python類中的多態(tài)性 Python類中的多態(tài)性 Jul 05, 2025 am 02:58 AM

多態(tài)是Python面向?qū)ο缶幊讨械暮诵母拍?,指“一種接口,多種實(shí)現(xiàn)”,允許統(tǒng)一處理不同類型的對象。 1.多態(tài)通過方法重寫實(shí)現(xiàn),子類可重新定義父類方法,如Animal類的speak()方法在Dog和Cat子類中有不同實(shí)現(xiàn)。 2.多態(tài)的實(shí)際用途包括簡化代碼結(jié)構(gòu)、增強(qiáng)可擴(kuò)展性,例如圖形繪製程序中統(tǒng)一調(diào)用draw()方法,或遊戲開發(fā)中處理不同角色的共同行為。 3.Python實(shí)現(xiàn)多態(tài)需滿足:父類定義方法,子類重寫該方法,但不要求繼承同一父類,只要對象實(shí)現(xiàn)相同方法即可,這稱為“鴨子類型”。 4.注意事項(xiàng)包括保持方

Python函數(shù)參數(shù)和參數(shù) Python函數(shù)參數(shù)和參數(shù) Jul 04, 2025 am 03:26 AM

參數(shù)(parameters)是定義函數(shù)時的佔(zhàn)位符,而傳參(arguments)是調(diào)用時傳入的具體值。 1.位置參數(shù)需按順序傳遞,順序錯誤會導(dǎo)致結(jié)果錯誤;2.關(guān)鍵字參數(shù)通過參數(shù)名指定,可改變順序且提高可讀性;3.默認(rèn)參數(shù)值在定義時賦值,避免重複代碼,但應(yīng)避免使用可變對像作為默認(rèn)值;4.args和*kwargs可處理不定數(shù)量的參數(shù),適用於通用接口或裝飾器,但應(yīng)謹(jǐn)慎使用以保持可讀性。

解釋Python發(fā)電機(jī)和迭代器。 解釋Python發(fā)電機(jī)和迭代器。 Jul 05, 2025 am 02:55 AM

迭代器是實(shí)現(xiàn)__iter__()和__next__()方法的對象,生成器是簡化版的迭代器,通過yield關(guān)鍵字自動實(shí)現(xiàn)這些方法。 1.迭代器每次調(diào)用next()返回一個元素,無更多元素時拋出StopIteration異常。 2.生成器通過函數(shù)定義,使用yield按需生成數(shù)據(jù),節(jié)省內(nèi)存且支持無限序列。 3.處理已有集合時用迭代器,動態(tài)生成大數(shù)據(jù)或需惰性求值時用生成器,如讀取大文件時逐行加載。注意:列表等可迭代對像不是迭代器,迭代器到盡頭後需重新創(chuàng)建,生成器只能遍歷一次。

python`@classmethod'裝飾師解釋了 python`@classmethod'裝飾師解釋了 Jul 04, 2025 am 03:26 AM

類方法是Python中通過@classmethod裝飾器定義的方法,其第一個參數(shù)為類本身(cls),用於訪問或修改類狀態(tài)。它可通過類或?qū)嵗{(diào)用,影響的是整個類而非特定實(shí)例;例如在Person類中,show_count()方法統(tǒng)計創(chuàng)建的對像數(shù)量;定義類方法時需使用@classmethod裝飾器並將首參命名為cls,如change_var(new_value)方法可修改類變量;類方法與實(shí)例方法(self參數(shù))、靜態(tài)方法(無自動參數(shù))不同,適用於工廠方法、替代構(gòu)造函數(shù)及管理類變量等場景;常見用途包括從

如何處理Python中的API身份驗(yàn)證 如何處理Python中的API身份驗(yàn)證 Jul 13, 2025 am 02:22 AM

處理API認(rèn)證的關(guān)鍵在於理解並正確使用認(rèn)證方式。 1.APIKey是最簡單的認(rèn)證方式,通常放在請求頭或URL參數(shù)中;2.BasicAuth使用用戶名和密碼進(jìn)行Base64編碼傳輸,適合內(nèi)部系統(tǒng);3.OAuth2需先通過client_id和client_secret獲取Token,再在請求頭中帶上BearerToken;4.為應(yīng)對Token過期,可封裝Token管理類自動刷新Token;總之,根據(jù)文檔選擇合適方式,並安全存儲密鑰信息是關(guān)鍵。

什麼是python魔法方法或dunder方法? 什麼是python魔法方法或dunder方法? Jul 04, 2025 am 03:20 AM

Python的magicmethods(或稱dunder方法)是用於定義對象行為的特殊方法,它們以雙下劃線開頭和結(jié)尾。 1.它們使對象能夠響應(yīng)內(nèi)置操作,如加法、比較、字符串表示等;2.常見用例包括對像初始化與表示(__init__、__repr__、__str__)、算術(shù)運(yùn)算(__add__、__sub__、__mul__)及比較運(yùn)算(__eq__、__lt__);3.使用時應(yīng)確保其行為符合預(yù)期,例如__repr__應(yīng)返回可重構(gòu)對象的表達(dá)式,算術(shù)方法應(yīng)返回新實(shí)例;4.應(yīng)避免過度使用或以令人困惑的方

Python內(nèi)存管理如何工作? Python內(nèi)存管理如何工作? Jul 04, 2025 am 03:26 AM

Pythonmanagesmemoryautomaticallyusingreferencecountingandagarbagecollector.Referencecountingtrackshowmanyvariablesrefertoanobject,andwhenthecountreacheszero,thememoryisfreed.However,itcannothandlecircularreferences,wheretwoobjectsrefertoeachotherbuta

python`@property`裝飾師 python`@property`裝飾師 Jul 04, 2025 am 03:28 AM

@property是Python中用於將方法偽裝成屬性的裝飾器,允許在訪問屬性時執(zhí)行邏輯判斷或動態(tài)計算值。 1.它通過@property裝飾器定義getter方法,使外部像訪問屬性一樣調(diào)用方法;2.搭配.setter可控制賦值行為,如校驗(yàn)值合法性,不定義.setter則為只讀屬性;3.適用於屬性賦值校驗(yàn)、動態(tài)生成屬性值、隱藏內(nèi)部實(shí)現(xiàn)細(xì)節(jié)等場景;4.使用時注意屬性名與私有變量名不同名,避免死循環(huán),適合輕量級操作;5.示例中Circle類限制radius非負(fù),Person類動態(tài)生成full_name屬

See all articles