今天是第 14 天,我回到了在運行 Flask 之前離開簡單的 Python 專案的地方。哈哈!編碼有時令人興奮,有時令人沮喪(或大多數時候...)。無論如何,您透過自己的經驗更了解。這就是為什麼我很高興記錄我的經歷。所以今天,我學習了Python模組、多態性、JSON、Math、Datetime、Scope和迭代器。讓我們深入了解一下。
Python 中的模組是包含 Python 程式碼(函數、變數或類別)的文件,可以在不同的腳本或專案中重複使用。創建模組可以促進程式碼重複使用,使您的專案更清晰、更模組化。
建立與匯入模組:
模組只是一個以 .py 副檔名儲存的 Python 檔案。您可以在一個模組中定義函數、變數和類別並將它們匯入到另一個模組中。
範例:建立和使用模組
# mymodule.py def greeting(name): print(f"Hello, {name}")
import mymodule mymodule.greeting("Jonathan") # Output: Hello, Jonathan
您也可以在匯入時為模組指定別名:
import mymodule as mx mx.greeting("Jane") # Output: Hello, Jane
使用內建模組:
Python 隨附許多內建模組。例如,您可以使用平台模組來檢索系統資訊:
import platform print(platform.system()) # Output: The OS you're running (e.g., Windows, Linux, etc.)
JSON(JavaScript 物件表示法)廣泛用於在 Web 應用程式中傳輸資料。 Python提供了json模組來解析和產生JSON。
解析 JSON:
您可以使用 json.loads() 將 JSON 字串轉換為 Python 字典。
import json json_data = '{ "name": "John", "age": 30, "city": "New York" }' parsed_data = json.loads(json_data) print(parsed_data['age']) # Output: 30
將 Python 物件轉換為 JSON:
您也可以使用 json.dumps() 將 Python 物件(例如,dict、list、tuple)轉換為 JSON 字串。
範例:
import json python_obj = {"name": "John", "age": 30, "city": "New York"} json_string = json.dumps(python_obj) print(json_string) # Output: {"name": "John", "age": 30, "city": "New York"}
格式化和自訂 JSON 輸出:
您可以使用 indent 參數讓 JSON 字串更具可讀性:
json_string = json.dumps(python_obj, indent=4) print(json_string)
這會輸出一個格式良好的 JSON 字串:
{ "name": "John", "age": 30, "city": "New York" }
Python 提供內建函數和數學模組來執行各種數學任務。
基本數學函數:
min() 和 max():找出可迭代物件中的最小值和最大值:
print(min(5, 10, 25)) # Output: 5 print(max(5, 10, 25)) # Output: 25
abs():傳回數字的絕對值:
print(abs(-7.25)) # Output: 7.25
pow():計算數字的冪:
print(pow(4, 3)) # Output: 64 (4 to the power of 3)
數學模組:
對於高階數學運算,數學模組提供了一組廣泛的函數。
import math print(math.sqrt(64)) # Output: 8.0
print(math.ceil(1.4)) # Output: 2 print(math.floor(1.4)) # Output: 1
print(math.pi) # Output: 3.141592653589793
4。使用日期:在 Python 中管理時間
Python 的 datetime 模組有助於管理日期和時間。您可以產生目前日期、提取特定組成部分(如年、月、日)或操作日期物件。
取得目前日期和時間:
datetime.now() 函數傳回目前日期和時間。
import datetime current_time = datetime.datetime.now() print(current_time) # Output: 2024-09-06 05:15:51.590708 (example)
建立特定日期:
您可以使用 datetime() 建構子建立自訂日期。
custom_date = datetime.datetime(2020, 5, 17) print(custom_date) # Output: 2020-05-17 00:00:00
使用 strftime() 格式化日期:
您可以使用 strftime() 將日期物件格式化為字串。
範例:
formatted_date = custom_date.strftime("%B %d, %Y") print(formatted_date) # Output: May 17, 2020
以下是 strftime() 中使用的一些常見格式代碼表:
Directive | Description | Example |
---|---|---|
%a | Short weekday | Wed |
%A | Full weekday | Wednesday |
%b | Short month name | Dec |
%B | Full month name | December |
%Y | Year (full) | 2024 |
%H | Hour (24-hour format) | 17 |
%I | Hour (12-hour format) | 05 |
Polymorphism refers to the ability of different objects to be treated as instances of the same class through a common interface. It allows methods to do different things based on the object it is acting upon.
Method Overriding
In Python, polymorphism is often achieved through method overriding. A subclass can provide a specific implementation of a method that is already defined in its superclass.
Example:
class Animal: def make_sound(self): pass class Dog(Animal): def make_sound(self): return "Woof!" class Cat(Animal): def make_sound(self): return "Meow!" # Using polymorphism def animal_sound(animal): print(animal.make_sound()) dog = Dog() cat = Cat() animal_sound(dog) # Output: Woof! animal_sound(cat) # Output: Meow!
In the above example, animal_sound() can handle both Dog and Cat objects because they both implement the make_sound() method, demonstrating polymorphism.
Operator Overloading
Polymorphism also allows you to define how operators behave with user-defined classes by overloading them.
Example:
class Vector: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) def __repr__(self): return f"Vector({self.x}, {self.y})" v1 = Vector(2, 3) v2 = Vector(4, 1) v3 = v1 + v2 print(v3) # Output: Vector(6, 4) Here, the + operator is overloaded to handle Vector objects, allowing us to add vectors using the + operator. 2. Iterators in Python An iterator is an object that allows you to traverse through a container, such as a list or tuple, and retrieve elements one by one. Python iterators implement two main methods: __iter__() and __next__(). Creating an Iterator You can create your own iterator by defining a class with __iter__() and __next__() methods. Example: python Copy code class CountDown: def __init__(self, start): self.start = start def __iter__(self): return self def __next__(self): if self.start <= 0: raise StopIteration current = self.start self.start -= 1 return current # Using the iterator cd = CountDown(5) for number in cd: print(number) # Output: 5, 4, 3, 2, 1
In this example, CountDown is an iterator that counts down from a starting number to 1.
Using Built-in Iterators
Python provides built-in iterators such as enumerate(), map(), and filter().
Example:
numbers = [1, 2, 3, 4, 5] squared = map(lambda x: x ** 2, numbers) for num in squared: print(num) # Output: 1, 4, 9, 16, 25
Here, map() applies a function to all items in the list and returns an iterator.
Scope determines the visibility of variables in different parts of the code. Python uses the LEGB rule to resolve names: Local, Enclosing, Global, and Built-in.
Local Scope
Variables created inside a function are local to that function.
Example:
def my_func(): x = 10 # Local variable print(x) my_func() # Output: 10
Here, x is accessible only within my_func().
Global Scope
Variables created outside any function are global and accessible from anywhere in the code.
Example:
Copy code x = 20 # Global variable def my_func(): print(x) my_func() print(x) # Output: 20, 20
Enclosing Scope
In nested functions, an inner function can access variables from its enclosing (outer) function.
Example:
def outer_func(): x = 30 def inner_func(): print(x) # Accessing variable from outer function inner_func() outer_func() # Output: 30
Global Keyword
To modify a global variable inside a function, use the global keyword.
Example:
x = 50 def my_func(): global x x = 60 my_func() print(x) # Output: 60
Nonlocal Keyword
The nonlocal keyword allows you to modify a variable in the nearest enclosing scope that is not global.
Example:
def outer_func(): x = 70 def inner_func(): nonlocal x x = 80 inner_func() print(x) outer_func() # Output: 80
In this example, nonlocal allows inner_func() to modify the x variable in outer_func().
Check out my #100daysofMiva repo on GitHub. Follow, Star and Share.
以上是#daysofMiva 的日子 ||掌握 Python 模組、JSON、數學和日期的詳細內容。更多資訊請關注PHP中文網其他相關文章!