Hari #daysofMiva || Menguasai Modul Python, JSON, Matematik dan Tarikh

王林
Lepaskan: 2024-09-07 14:30:32
asal
378 orang telah melayarinya

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

Ini Hari #14 dan saya kembali ke tempat saya meninggalkan projek ular sawa ringkas saya sebelum berlari ke kelalang. Lol! Pengekodan boleh menjadi menarik, dan kadangkala juga mengecewakan (atau sering kali...). Bagaimanapun, anda lebih tahu melalui pengalaman anda. Itulah sebabnya saya teruja mendokumentasikan saya. Jadi hari ini, saya mempelajari modul Python, polimorfisme, JSON, Matematik, Datetime, Skop dan iterator. Jom selami.

1. Modul Python: Membina Perpustakaan Kod Boleh Digunakan Semula

Modul dalam Python ialah fail yang mengandungi kod Python (fungsi, pembolehubah atau kelas) yang boleh digunakan semula merentas skrip atau projek yang berbeza. Mencipta modul menggalakkan penggunaan semula kod, menjadikan projek anda lebih bersih dan lebih modular.

Mencipta dan Mengimport Modul:

Modul hanyalah fail Python yang disimpan dengan sambungan .py. Anda boleh menentukan fungsi, pembolehubah dan kelas dalam satu modul dan mengimportnya ke dalam yang lain.

Contoh: Mencipta dan Menggunakan Modul

  1. Buat fail bernama mymodule.py dengan kandungan berikut:
# mymodule.py
def greeting(name):
    print(f"Hello, {name}")
Salin selepas log masuk
  1. Sekarang, import modul dalam skrip Python yang lain:
import mymodule

mymodule.greeting("Jonathan")  # Output: Hello, Jonathan
Salin selepas log masuk

Anda juga boleh memberikan alias kepada modul semasa mengimport:

import mymodule as mx

mx.greeting("Jane")  # Output: Hello, Jane
Salin selepas log masuk

Menggunakan Modul Terbina dalam:

Python datang dengan banyak modul terbina dalam. Sebagai contoh, anda boleh menggunakan modul platform untuk mendapatkan maklumat sistem:

import platform

print(platform.system())  # Output: The OS you're running (e.g., Windows, Linux, etc.)
Salin selepas log masuk

2. Bekerja dengan JSON dalam Python: Menghuraikan dan Menjana Data JSON

JSON (JavaScript Object Notation) digunakan secara meluas untuk menghantar data dalam aplikasi web. Python menyediakan modul json untuk menghuraikan dan menjana JSON.

Menghuraikan JSON:

Anda boleh menukar rentetan JSON kepada kamus Python menggunakan json.loads().

import json

json_data = '{ "name": "John", "age": 30, "city": "New York" }'
parsed_data = json.loads(json_data)

print(parsed_data['age'])  # Output: 30
Salin selepas log masuk

Menukar Objek Python kepada JSON:

Anda juga boleh menukar objek Python (cth., dict, list, tuple) kepada rentetan JSON menggunakan json.dumps().

Contoh:

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"}
Salin selepas log masuk

Memformat dan Menyesuaikan Output JSON:

Anda boleh menjadikan rentetan JSON lebih mudah dibaca dengan menggunakan parameter inden:

json_string = json.dumps(python_obj, indent=4)
print(json_string)
Salin selepas log masuk

Ini menghasilkan rentetan JSON yang diformat dengan baik:

{
    "name": "John",
    "age": 30,
    "city": "New York"
}
Salin selepas log masuk

3. Python Math: Melakukan Operasi Matematik

Python menyediakan kedua-dua fungsi terbina dalam dan modul matematik untuk melaksanakan pelbagai tugasan matematik.

Fungsi Asas Matematik:

min() dan max(): Untuk mencari nilai minimum dan maksimum dalam iterable:

print(min(5, 10, 25))  # Output: 5
print(max(5, 10, 25))  # Output: 25
Salin selepas log masuk

abs(): Mengembalikan nilai mutlak nombor:

print(abs(-7.25))  # Output: 7.25
Salin selepas log masuk

pow(): Mengira kuasa nombor:

print(pow(4, 3))  # Output: 64 (4 to the power of 3)
Salin selepas log masuk

Modul Matematik:

Untuk operasi matematik lanjutan, modul matematik menawarkan set fungsi yang luas.

  • Akar Kuasa Dua: Menggunakan math.sqrt():
import math

print(math.sqrt(64))  # Output: 8.0
Salin selepas log masuk
  • Siling dan Lantai: Membundarkan nombor ke atas atau ke bawah:
print(math.ceil(1.4))  # Output: 2
print(math.floor(1.4))  # Output: 1
Salin selepas log masuk
  • Pemalar PI: Mengakses nilai π:
print(math.pi)  # Output: 3.141592653589793
Salin selepas log masuk

4. Bekerja dengan Tarikh: Mengurus Masa dalam Python

Modul datetime Python membantu mengurus tarikh dan masa. Anda boleh menjana tarikh semasa, mengekstrak komponen tertentu (seperti tahun, bulan, hari) atau memanipulasi objek tarikh.

Mendapatkan Tarikh dan Masa Semasa:

Fungsi datetime.now() mengembalikan tarikh dan masa semasa.

import datetime

current_time = datetime.datetime.now()
print(current_time)
# Output: 2024-09-06 05:15:51.590708 (example)
Salin selepas log masuk

Membuat Tarikh Tertentu:

Anda boleh mencipta tarikh tersuai menggunakan pembina datetime().

custom_date = datetime.datetime(2020, 5, 17)
print(custom_date)  # Output: 2020-05-17 00:00:00
Salin selepas log masuk

Memformat Tarikh dengan strftime():

Anda boleh memformat objek tarikh menjadi rentetan menggunakan strftime().

Contoh:

formatted_date = custom_date.strftime("%B %d, %Y")
print(formatted_date)  # Output: May 17, 2020
Salin selepas log masuk

Berikut ialah jadual beberapa kod format biasa yang digunakan dalam 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!
Salin selepas log masuk

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
Salin selepas log masuk

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
Salin selepas log masuk

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
Salin selepas log masuk

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
Salin selepas log masuk

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
Salin selepas log masuk

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
Salin selepas log masuk

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
Salin selepas log masuk

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.

Atas ialah kandungan terperinci Hari #daysofMiva || Menguasai Modul Python, JSON, Matematik dan Tarikh. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!