#daysofMiva の日 || Python モジュール、JSON、数学、日付をマスターする
#14 になり、flask に向かう前に単純な Python プロジェクトを残した場所に戻りました。笑!コーディングはエキサイティングなことでもありますが、時にはイライラすることもあります (ほとんどの場合はそうでしょうか...)。とにかく、あなたは経験を通してよく知っています。だからこそ、私は自分のことを記録することに興奮しています。そこで今日は、Python モジュール、ポリモーフィズム、JSON、Math、Datetime、Scope、イテレーターについて学びました。さあ、飛び込みましょう。
1. Python モジュール: 再利用可能なコード ライブラリの構築
Python のモジュールは、さまざまなスクリプトまたはプロジェクト間で再利用できる Python コード (関数、変数、またはクラス) を含むファイルです。モジュールを作成するとコードの再利用が促進され、プロジェクトがよりクリーンになり、よりモジュール化されます。
モジュールの作成とインポート:
モジュールは、.py 拡張子で保存された単なる Python ファイルです。 1 つのモジュールで関数、変数、クラスを定義し、それらを別のモジュールにインポートできます。
例: モジュールの作成と使用
- 次の内容を含む mymodule.py というファイルを作成します。
# mymodule.py def greeting(name): print(f"Hello, {name}")
- 次に、モジュールを別の Python スクリプトにインポートします。
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.)
2. Python での JSON の操作: JSON データの解析と生成
JSON (JavaScript Object Notation) は、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 オブジェクト (辞書、リスト、タプルなど) を 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 出力のフォーマットとカスタマイズ:
インデントパラメータを使用すると、JSON 文字列を読みやすくできます。
json_string = json.dumps(python_obj, indent=4) print(json_string)
これにより、適切な形式の JSON 文字列が出力されます。
{ "name": "John", "age": 30, "city": "New York" }
3. Python 数学: 数学演算の実行
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)
数学モジュール:
高度な数学演算のために、数学モジュールは広範な関数セットを提供します。
- 平方根: math.sqrt() の使用:
import math print(math.sqrt(64)) # Output: 8.0
- 天井と床: 数値を切り上げまたは切り捨てます:
print(math.ceil(1.4)) # Output: 2 print(math.floor(1.4)) # Output: 1
- PI 定数: π の値へのアクセス:
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 in Python
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 in Python
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 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undress AI Tool
脱衣画像を無料で

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

Pyodbcのインストール:Pipinstallpyodbcコマンドを使用してライブラリをインストールします。 2.接続sqlserver:pyodbc.connect()メソッドを介して、ドライバー、サーバー、データベース、uid/pwdまたはtrusted_connectionを含む接続文字列を使用し、それぞれSQL認証またはWindows認証をサポートします。 3.インストールされているドライバーを確認します:pyodbc.drivers()を実行し、「sqlserver」を含むドライバー名をフィルタリングして、「sqlserverのodbcdriver17」などの正しいドライバー名が使用されるようにします。 4.接続文字列の重要なパラメーター

httpx.asyncclientを使用して、非同期httpリクエストを効率的に開始します。 1.基本的なGETリクエストは、asyncwithを介してクライアントを管理し、awaitclient.getを使用して非ブロッキングリクエストを開始します。 2。asyncio.gatherを組み合わせてasyncio.gatherを組み合わせると、パフォーマンスが大幅に向上する可能性があり、合計時間は最も遅いリクエストに等しくなります。 3.カスタムヘッダー、認証、base_url、タイムアウト設定をサポートします。 4。投稿リクエストを送信してJSONデータを伝達できます。 5.同期非同期コードの混合を避けるために注意してください。プロキシサポートは、クローラーやAPI集約、その他のシナリオに適したバックエンド互換性に注意を払う必要があります。

Pythoncanbeoptimizedformemory-boundoperationsは、ヘッドゲネレーター、EfficientDataStructures、およびManagingObjectlifetimes.first、Usegeneratoratoratoratoratoratoraturatussを使用していることを確認してください

この記事の目的は、Sqlalchemyの初心者がCreate_Engineを使用したときに遭遇した「removedin20warning」警告を解決することを支援することを支援することを支援することを支援することを目的としています。この記事では、この警告の原因を詳細に説明し、特定の手順とコード例を提供して、警告と接続の問題を排除し、データベースをスムーズにクエリして操作できるようにします。

shutil.rmtree()は、ディレクトリツリー全体を再帰的に削除するPythonの関数です。指定されたフォルダーとすべてのコンテンツを削除できます。 1.基本的な使用法:shutil.rmtree(PATH)を使用してディレクトリを削除すると、FilenotFounderror、PermissionError、その他の例外を処理する必要があります。 2。実用的なアプリケーション:一時的なデータやキャッシュディレクトリなど、サブディレクトリとファイルを1回クリックして含むフォルダーをクリアできます。 3。注:削除操作は復元されません。 FilenotFounderrorは、パスが存在しない場合に投げられます。許可またはファイル職業のために失敗する可能性があります。 4.オプションのパラメーター:INGRORE_ERRORS = trueでエラーを無視できます

対応するデータベースドライバーをインストールします。 2。CONNECT()を使用してデータベースに接続します。 3.カーソルオブジェクトを作成します。 4。Execute()またはexecuteMany()を使用してSQLを実行し、パラメーター化されたクエリを使用して噴射を防ぎます。 5。Fetchall()などを使用して結果を得る。 6。COMMING()は、変更後に必要です。 7.最後に、接続を閉じるか、コンテキストマネージャーを使用して自動的に処理します。完全なプロセスにより、SQL操作が安全で効率的であることが保証されます。

Pythonは、ETLプロセスを実装するための効率的なツールです。 1。データ抽出:データベース、API、ファイル、およびその他のソースからデータを抽出できます。Pandas、Sqlalchemy、Requests、その他のライブラリを介して。 2。データ変換:パンダを使用して、クリーニング、タイプ変換、関連性、集約、その他の操作を使用して、データの品質を確保し、パフォーマンスを最適化します。 3。データの読み込み:PandasのTO_SQLメソッドまたはクラウドプラットフォームSDKを使用して、ターゲットシステムにデータを書き込み、書き込み方法とバッチ処理に注意してください。 4。ツールの推奨事項:気流、ダグスター、長官は、ログアラームと仮想環境を組み合わせて、安定性と保守性を向上させるために、プロセスのスケジューリングと管理に使用されます。

psycopg2.pool.simpleconnectionPoolを使用して、データベース接続を効果的に管理し、頻繁な接続の作成と破壊によって引き起こされるパフォーマンスオーバーヘッドを回避します。 1.接続プールを作成するときは、接続プールが正常に初期化されていることを確認するために、接続パラメーターとデータベース接続パラメーターの最小数と最大数を指定します。 2。getConn()を介して接続を取得し、putconn()を使用して、データベース操作を実行した後に接続をプールに戻します。絶えずconn.close()を呼び出すことは禁止されています。 3. SimpleConnectionPoolはスレッドセーフであり、マルチスレッド環境に適しています。 4.コンテキストマネージャーと組み合わせてコンテキストマネージャーを実装して、例外が記載されているときに接続を正しく返すことができることを確認することをお勧めします。
