p

python

這段程式碼使用 pydantic 來定義使用者模型,並且透過 Streamlit 在網頁上顯示使用者資訊,同時 pretty_errors 提供美觀的錯誤訊息格式。

0 0 0 1
1 from datetime import date
2
3 import pretty_errors
4 import streamlit as st
5 from pydantic import BaseModel, Field
6
7
8 class User(BaseModel):
9 id: int
10 name: str

這段程式碼示範了 Python 的類別繼承機制,透過 Person(人)和 Employee(員工)類別,展現子類別如何繼承父類別的屬性與方法,並添加自己的功能。

0 0 0 1
1 # 定義 Person 類別
2 class Person:
3 # 定義建構子
4 def __init__(self, name):
5 # 設定人的名字
6 self.name = name
7
8 # 定義取得人的名字的方法
9 def get_name(self):
10 """取得人的名字"""

這段程式碼用於模擬擲硬幣 n 次,並統計正面與反面的機率。程式會計算並顯示正面與反面的出現次數與機率,以驗證隨機性。

0 0 0 1
1 import random
2
3
4 def toss_coin():
5 # 0代表正面,1代表反面
6 return "正面" if random.randint(0, 1) == 0 else "反面"
7
8
9 def simulate_tosses(n):
10 # 初始化計數器

這段 Python 程式碼 使用 contextlib.contextmanager 來建立一個 自訂的上下文管理器 (ic_disabled()),用於 暫時停用 icecream (ic) 的輸出,並在 離開上下文後復原原始狀態。

0 0 0 1
1 # 引用python內建模組contextlib中的contextmanager
2 from contextlib import contextmanager
3
4 # 將icecream模組簡稱為ic
5 from icecream import ic # 引用icecream模組
6
7 # 設定icecream的輸出選項,包含上下文
8 ic.configureOutput(includeContext=True)
9
10 # 定義ic_disabled函式為一個上下文管理器

這段 Python 程式碼 展示了 參數解包 (Argument Unpacking) 的應用方式,包括 列表解包 (*args) 和 字典解包 (**kwargs),用於函式呼叫時動態傳遞參數。

0 0 0 1
1 assert list(range(3, 6)) == [3, 4, 5]
2
3 arguments_list = [3, 6]
4 assert list(range(*arguments_list)) == [3, 4, 5]
5
6
7 def function_that_receives_names_arguments(first_word, second_word):
8 return first_word + ", " + second_word + "!"
9

這段 Python 程式碼 使用 多執行緒 (Threading) 與工作佇列 (Queue) 來 處理 30 個工作項目,確保所有工作都執行完畢後,才會顯示 "All work completed" 訊息。

0 0 0 1
1 """
2 這段程式碼是建立一個執行緒來處理工作項目,並將 30 個工作項目放入工作佇列中。然後會等待所有工作都完成後才會印出 "All work completed" 的訊息。
3 """
4
5 import threading
6 import queue
7
8
9 # 定義一個函式來處理工作項目
10 def process_work_item(work_queue):