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