首页 后端开发 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. 创建一个名为 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 对象表示法)广泛用于在 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"
}
登录后复制

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中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

<🎜>:泡泡胶模拟器无穷大 - 如何获取和使用皇家钥匙
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系统,解释
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆树的耳语 - 如何解锁抓钩
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1670
14
CakePHP 教程
1428
52
Laravel 教程
1329
25
PHP教程
1274
29
C# 教程
1256
24
Python与C:学习曲线和易用性 Python与C:学习曲线和易用性 Apr 19, 2025 am 12:20 AM

Python更易学且易用,C 则更强大但复杂。1.Python语法简洁,适合初学者,动态类型和自动内存管理使其易用,但可能导致运行时错误。2.C 提供低级控制和高级特性,适合高性能应用,但学习门槛高,需手动管理内存和类型安全。

Python和时间:充分利用您的学习时间 Python和时间:充分利用您的学习时间 Apr 14, 2025 am 12:02 AM

要在有限的时间内最大化学习Python的效率,可以使用Python的datetime、time和schedule模块。1.datetime模块用于记录和规划学习时间。2.time模块帮助设置学习和休息时间。3.schedule模块自动化安排每周学习任务。

Python vs.C:探索性能和效率 Python vs.C:探索性能和效率 Apr 18, 2025 am 12:20 AM

Python在开发效率上优于C ,但C 在执行性能上更高。1.Python的简洁语法和丰富库提高开发效率。2.C 的编译型特性和硬件控制提升执行性能。选择时需根据项目需求权衡开发速度与执行效率。

Python vs. C:了解关键差异 Python vs. C:了解关键差异 Apr 21, 2025 am 12:18 AM

Python和C 各有优势,选择应基于项目需求。1)Python适合快速开发和数据处理,因其简洁语法和动态类型。2)C 适用于高性能和系统编程,因其静态类型和手动内存管理。

学习Python:2小时的每日学习是否足够? 学习Python:2小时的每日学习是否足够? Apr 18, 2025 am 12:22 AM

每天学习Python两个小时是否足够?这取决于你的目标和学习方法。1)制定清晰的学习计划,2)选择合适的学习资源和方法,3)动手实践和复习巩固,可以在这段时间内逐步掌握Python的基本知识和高级功能。

Python标准库的哪一部分是:列表或数组? Python标准库的哪一部分是:列表或数组? Apr 27, 2025 am 12:03 AM

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

Python:自动化,脚本和任务管理 Python:自动化,脚本和任务管理 Apr 16, 2025 am 12:14 AM

Python在自动化、脚本编写和任务管理中表现出色。1)自动化:通过标准库如os、shutil实现文件备份。2)脚本编写:使用psutil库监控系统资源。3)任务管理:利用schedule库调度任务。Python的易用性和丰富库支持使其在这些领域中成为首选工具。

Web开发的Python:关键应用程序 Web开发的Python:关键应用程序 Apr 18, 2025 am 12:20 AM

Python在Web开发中的关键应用包括使用Django和Flask框架、API开发、数据分析与可视化、机器学习与AI、以及性能优化。1.Django和Flask框架:Django适合快速开发复杂应用,Flask适用于小型或高度自定义项目。2.API开发:使用Flask或DjangoRESTFramework构建RESTfulAPI。3.数据分析与可视化:利用Python处理数据并通过Web界面展示。4.机器学习与AI:Python用于构建智能Web应用。5.性能优化:通过异步编程、缓存和代码优

See all articles