timmy / Python 類別與屬性訪問器

0 curtidas
0 bifurcações
1 arquivos
Última atividade 10 months ago
此程式展示 Python 類別的屬性封裝,透過 @property 定義 getter 和 setter 方法,實現安全的屬性訪問與修改,並根據年齡決定遊戲類型。
1 class Person(object):
2
3 def __init__(self, name, age):
4 self._name = name
5 self._age = age
6
7 # 訪問器 - getter方法
8 @property
9 def name(self):
10 return self._name

timmy / Python 單元測試與函式驗證

0 curtidas
0 bifurcações
1 arquivos
Última atividade 10 months ago
這段程式碼使用 Python 的 unittest 模組進行單元測試,測試 add(x, y) 函式是否正確運算兩個數字的加總。
1 import unittest
2
3
4 def add(x, y):
5 return x + y
6
7
8 class TestAdd(unittest.TestCase):
9
10 def test_add_two_numbers(self):

timmy / 使用 Streamlit 與 Pydantic 建立使用者資訊展示

0 curtidas
0 bifurcações
1 arquivos
Última atividade 10 months ago
這段程式碼使用 pydantic 來定義使用者模型,並且透過 Streamlit 在網頁上顯示使用者資訊,同時 pretty_errors 提供美觀的錯誤訊息格式。
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

timmy / Python 類別與繼承示範

0 curtidas
0 bifurcações
1 arquivos
Última atividade 10 months ago
這段程式碼示範了 Python 的類別繼承機制,透過 Person(人)和 Employee(員工)類別,展現子類別如何繼承父類別的屬性與方法,並添加自己的功能。
1 # 定義 Person 類別
2 class Person:
3 # 定義建構子
4 def __init__(self, name):
5 # 設定人的名字
6 self.name = name
7
8 # 定義取得人的名字的方法
9 def get_name(self):
10 """取得人的名字"""

timmy / 檢查 Python 套件是否已安裝

0 curtidas
0 bifurcações
1 arquivos
Última atividade 10 months ago
這段程式碼用於檢查 Python 環境中是否安裝了 numpy 模組。 如果 numpy 已安裝,則輸出 "numpy is installed",否則輸出 "numpy is not installed"。
1 from importlib.util import find_spec
2
3 if find_spec("numpy") is not None:
4 print("numpy is installed")
5 else:
6 print("numpy is not installed")

timmy / 模擬硬幣擲投並計算機率

0 curtidas
0 bifurcações
1 arquivos
Última atividade 10 months ago
這段程式碼用於模擬擲硬幣 n 次,並統計正面與反面的機率。程式會計算並顯示正面與反面的出現次數與機率,以驗證隨機性。
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 # 初始化計數器

timmy / 隨機模擬擲硬幣

0 curtidas
0 bifurcações
1 arquivos
Última atividade 10 months ago
這段程式碼模擬擲硬幣(Toss a Coin)的行為,每次執行都會隨機回傳「正面」或「反面」。
1 import random
2
3
4 def toss_coin():
5 # 0代表正面,1代表反面
6 return "正面" if random.randint(0, 1) == 0 else "反面"
7
8
9 # 擲硬幣
10 result = toss_coin()

timmy / Python 參數解包 (*args 和 **kwargs)

0 curtidas
0 bifurcações
1 arquivos
Última atividade 10 months ago
這段 Python 程式碼 展示了 參數解包 (Argument Unpacking) 的應用方式,包括 列表解包 (*args) 和 字典解包 (**kwargs),用於函式呼叫時動態傳遞參數。
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