ホームページ バックエンド開発 Python チュートリアル #daysofMiva の日 || Python モジュール、JSON、数学、日付をマスターする

#daysofMiva の日 || Python モジュール、JSON、数学、日付をマスターする

Sep 07, 2024 pm 02:30 PM

Day of #daysofMiva || Mastering Python Modules, JSON, Math, and Dates

#14 になり、flask に向かう前に単純な Python プロジェクトを残した場所に戻りました。笑!コーディングはエキサイティングなことでもありますが、時にはイライラすることもあります (ほとんどの場合はそうでしょうか...)。とにかく、あなたは経験を通してよく知っています。だからこそ、私は自分のことを記録することに興奮しています。そこで今日は、Python モジュール、ポリモーフィズム、JSON、Math、Datetime、Scope、イテレーターについて学びました。さあ、飛び込みましょう。

1. Python モジュール: 再利用可能なコード ライブラリの構築

Python のモジュールは、さまざまなスクリプトまたはプロジェクト間で再利用できる Python コード (関数、変数、またはクラス) を含むファイルです。モジュールを作成するとコードの再利用が促進され、プロジェクトがよりクリーンになり、よりモジュール化されます。

モジュールの作成とインポート:

モジュールは、.py 拡張子で保存された単なる Python ファイルです。 1 つのモジュールで関数、変数、クラスを定義し、それらを別のモジュールにインポートできます。

例: モジュールの作成と使用

  1. 次の内容を含む mymodule.py というファイルを作成します。
# mymodule.py
def greeting(name):
    print(f"Hello, {name}")
  1. 次に、モジュールを別の 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 サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Stock Market GPT

Stock Market GPT

AIを活用した投資調査により賢明な意思決定を実現

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

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

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

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

ホットトピック

pythonでrequastion.txtファイルからパッケージをインストールする方法 pythonでrequastion.txtファイルからパッケージをインストールする方法 Sep 18, 2025 am 04:24 AM

Pipinstall-rrequirements.txtを実行して、依存関係パッケージをインストールします。競合を回避し、ファイルパスが正しく、PIPが更新されていることを確認し、必要に応じて-no-depsや-userなどのオプションを使用して、必要に応じてインストール動作を調整することを確認して、最初に仮想環境を作成およびアクティブ化することをお勧めします。

PEFT LORAアダプターとベースモデルの効率的なマージ戦略 PEFT LORAアダプターとベースモデルの効率的なマージ戦略 Sep 19, 2025 pm 05:12 PM

このチュートリアルは、PEFT LORAアダプターをベースモデルと効率的にマージして、完全に独立したモデルを生成する方法を詳しく説明しています。この記事は、トランスフォーマーを直接使用することは間違っていることを指摘しています。Automodelはアダプターをロードし、重みを手動でマージし、PEFTライブラリでMerge_and_unloadメソッドを使用する正しいプロセスを提供します。さらに、このチュートリアルでは、単語セグメントターを扱うことの重要性も強調し、PEFTバージョンの互換性の問題とソリューションについて説明しています。

PytestでPythonコードをテストする方法 PytestでPythonコードをテストする方法 Sep 20, 2025 am 12:35 AM

Pythonは、Pythonのシンプルで強力なテストツールです。インストール後、命名ルールに従ってテストファイルが自動的に発見されます。アサーションテストのためにtest_から始まる関数を書き込み、 @pytest.fixtureを使用して再利用可能なテストデータを作成し、pytest.raisesを使用して例外を確認し、指定されたテストと複数のコマンドラインオプションをサポートし、テスト効率を改善します。

Pythonのコマンドライン引数を処理する方法 Pythonのコマンドライン引数を処理する方法 Sep 21, 2025 am 03:49 AM

theargparsemoduleisttherecommendedwayto handlecommand-lineargumentsinpython、robustparsing、typevalidation、helpmessages、およびerrorhandling; ousesys.argvforsimplecasesrequiringminimalsetup。

Pythonの浮動小数点数の精度の問題とその高精度計算スキーム Pythonの浮動小数点数の精度の問題とその高精度計算スキーム Sep 19, 2025 pm 05:57 PM

この記事の目的は、PythonとNumpyの浮動小数点数の計算精度が不十分であるという一般的な問題を調査し、その根本原因は標準64ビットの浮動小数点数の表現制限にあることを説明しています。より高い精度を必要とするシナリオを計算するために、この記事では、MPMATH、Sympy、GMPYなどの高精度数学ライブラリの使用方法、機能、および適用可能なシナリオを導入して比較し、読者が複雑な精度のニーズを解決するための適切なツールを選択できるようにします。

PythonでPDFファイルを使用する方法 PythonでPDFファイルを使用する方法 Sep 20, 2025 am 04:44 AM

PYPDF2、PDFPlumber、およびFPDFは、PDFを処理するPythonのコアライブラリです。 pypdf2を使用して、pdfreaderを介してページを読み取り、extract_text()を呼び出してコンテンツを取得するなど、テキスト抽出、マージ、分割、暗号化を実行します。 PDFPlumberは、レイアウトテキストの抽出とテーブル認識を保持するのに適しており、Extract_Tables()をサポートしてテーブルデータを正確にキャプチャします。 FPDF(推奨されるFPDF2)はPDFを生成するために使用され、ドキュメントが構築され、add_page()、set_font()、およびcell()を介して出力されます。 PDFSをマージすると、PDFWriterのAppend()メソッドは複数のファイルを統合できます

Python現在の時間例を取得します Python現在の時間例を取得します Sep 15, 2025 am 02:32 AM

現在の時間を取得することは、DateTimeモジュールを介してPythonで実装できます。 1。DateTime.Now()を使用してローカル現在の時間を取得します。 Depcated Utcnow()、および日常業務は、datetime.now()とフォーマットされた文字列を組み合わせてニーズを満たすことができます。

Pythonの@ContextManagerデコレーターを使用してコンテキストマネージャーを作成するにはどうすればよいですか? Pythonの@ContextManagerデコレーターを使用してコンテキストマネージャーを作成するにはどうすればよいですか? Sep 20, 2025 am 04:50 AM

@ContextManagerFromContextLibandDefineAgeneratoratoraturationは、sexactlyOnceを使用します

See all articles