


Es ist Tag Nr. 14 und ich bin wieder da, wo ich meine einfachen Python-Projekte zurückgelassen habe, bevor ich zum Flask gelaufen bin. Lol! Codieren kann aufregend und manchmal auch frustrierend sein (oder ist es meistens ...). Wie auch immer, Sie wissen es durch Ihre Erfahrungen besser. Deshalb freue ich mich darauf, meine zu dokumentieren. Heute habe ich Python-Module, Polymorphismus, JSON, Mathematik, Datetime, Scope und Iteratoren gelernt. Lass uns eintauchen.
1. Python-Module: Erstellen wiederverwendbarer Codebibliotheken
Module in Python sind Dateien, die Python-Code (Funktionen, Variablen oder Klassen) enthalten, der in verschiedenen Skripten oder Projekten wiederverwendet werden kann. Das Erstellen von Modulen fördert die Wiederverwendung von Code und macht Ihre Projekte sauberer und modularer.
Module erstellen und importieren:
Ein Modul ist einfach eine Python-Datei, die mit der Erweiterung .py gespeichert wird. Sie können Funktionen, Variablen und Klassen in einem Modul definieren und in ein anderes importieren.
Beispiel: Erstellen und Verwenden eines Moduls
- Erstellen Sie eine Datei namens mymodule.py mit folgendem Inhalt:
# mymodule.py def greeting(name): print(f"Hello, {name}")
- Importieren Sie nun das Modul in ein anderes Python-Skript:
import mymodule mymodule.greeting("Jonathan") # Output: Hello, Jonathan
Sie können einem Modul beim Importieren auch einen Alias zuweisen:
import mymodule as mx mx.greeting("Jane") # Output: Hello, Jane
Verwendung integrierter Module:
Python verfügt über viele integrierte Module. Sie können beispielsweise das Plattformmodul verwenden, um Systeminformationen abzurufen:
import platform print(platform.system()) # Output: The OS you're running (e.g., Windows, Linux, etc.)
2. Arbeiten mit JSON in Python: Parsen und Generieren von JSON-Daten
JSON (JavaScript Object Notation) wird häufig zur Datenübertragung in Webanwendungen verwendet. Python stellt das JSON-Modul zum Parsen und Generieren von JSON bereit.
JSON analysieren:
Sie können einen JSON-String mit json.loads() in ein Python-Wörterbuch konvertieren.
import json json_data = '{ "name": "John", "age": 30, "city": "New York" }' parsed_data = json.loads(json_data) print(parsed_data['age']) # Output: 30
Konvertieren von Python-Objekten in JSON:
Sie können Python-Objekte (z. B. Diktat, Liste, Tupel) auch mit json.dumps() in einen JSON-String konvertieren.
Beispiel:
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-Ausgabe formatieren und anpassen:
Sie können die JSON-Zeichenfolge besser lesbar machen, indem Sie den Parameter „indent“ verwenden:
json_string = json.dumps(python_obj, indent=4) print(json_string)
Dies gibt eine gut formatierte JSON-Zeichenfolge aus:
{ "name": "John", "age": 30, "city": "New York" }
3. Python Math: Mathematische Operationen durchführen
Python bietet sowohl integrierte Funktionen als auch das Mathematikmodul zur Ausführung einer Vielzahl mathematischer Aufgaben.
Grundlegende mathematische Funktionen:
min() und max(): So finden Sie die Minimal- und Maximalwerte in einer Iteration:
print(min(5, 10, 25)) # Output: 5 print(max(5, 10, 25)) # Output: 25
abs(): Gibt den absoluten Wert einer Zahl zurück:
print(abs(-7.25)) # Output: 7.25
pow(): Berechnet die Potenz einer Zahl:
print(pow(4, 3)) # Output: 64 (4 to the power of 3)
Das Mathematikmodul:
Für fortgeschrittene mathematische Operationen bietet das Mathematikmodul einen umfangreichen Funktionsumfang.
- Quadratwurzel: Mit math.sqrt():
import math print(math.sqrt(64)) # Output: 8.0
- Decke und Boden: Rundet eine Zahl auf oder ab:
print(math.ceil(1.4)) # Output: 2 print(math.floor(1.4)) # Output: 1
- PI-Konstante: Zugriff auf den Wert von π:
print(math.pi) # Output: 3.141592653589793
4. Arbeiten mit Datumsangaben: Zeitverwaltung in Python
Das Datetime-Modul von Python hilft bei der Verwaltung von Datums- und Uhrzeitangaben. Sie können das aktuelle Datum generieren, bestimmte Komponenten (wie Jahr, Monat, Tag) extrahieren oder Datumsobjekte bearbeiten.
Abrufen des aktuellen Datums und der aktuellen Uhrzeit:
Die Funktion datetime.now() gibt das aktuelle Datum und die aktuelle Uhrzeit zurück.
import datetime current_time = datetime.datetime.now() print(current_time) # Output: 2024-09-06 05:15:51.590708 (example)
Ein bestimmtes Datum erstellen:
Sie können ein benutzerdefiniertes Datum mit dem datetime()-Konstruktor erstellen.
custom_date = datetime.datetime(2020, 5, 17) print(custom_date) # Output: 2020-05-17 00:00:00
Datumsangaben mit strftime() formatieren:
Sie können Datumsobjekte mit strftime() in Zeichenfolgen formatieren.
Beispiel:
formatted_date = custom_date.strftime("%B %d, %Y") print(formatted_date) # Output: May 17, 2020
Hier ist eine Tabelle mit einigen gängigen Formatcodes, die in strftime() verwendet werden:
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 <p>In this example, CountDown is an iterator that counts down from a starting number to 1.</p> <p><strong>Using Built-in Iterators</strong><br> Python provides built-in iterators such as enumerate(), map(), and filter().</p> <p>Example:<br> </p> <pre class="brush:php;toolbar:false"> 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.
The above is the detailed content of Day of #daysofMiva || Mastering Python Modules, JSON, Math, and Dates. For more information, please follow other related articles on the PHP Chinese website!

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version
Chinese version, very easy to use

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
