Python Documentation
website·Indexed 31 days ago
https://python.a-nomad.com/A comprehensive guide to Python covering basic syntax, data types, and object-oriented programming, as well as advanced topics including decorators, coroutines, multithreading, and garbage collection. Includes detailed sections on data structures (linked lists, stacks, queues, trees), algorithms, and database interactions with MySQL, Redis, and MongoDB.
What's inside Python
- Python is a high-level programming language characterized as interpreted, object-oriented, and dynamically typed. Key advantages include being simple to learn, free, portable, and possessing a rich set of extension libraries. Because it is an interpreted language, it executes code line-by-line via an interpreter, which may result in slower execution speeds compared to compiled languages like C/C++.
Overview of Python basic data types
Python uses dynamic typing, meaning the interpreter automatically infers the data type at runtime without requiring explicit declarations. The primary data types include:
Numeric Types:
int: Integersfloat: Floating-point numbersbool: Booleans (True/False; 0 is False, non-zero is True)complex: Complex numbers
Non-Numeric Types:
str: Stringslist: Liststuple: Tuplesdict: Dictionaries
Understand the TCP/IP Protocol Stack
The TCP/IP protocol suite is the industrial standard for LAN and WAN communication. It consists of four layers, each with specific responsibilities:
- Link Layer (Network Interface Layer): Handles physical interface details and hardware drivers. Key protocols include ARP (Address Resolution Protocol) and RARP (Reverse Address Resolution Protocol) to link link-layer addresses to network-layer addresses.
- Network Layer: Handles packet routing. Key protocols include IP (Internet Protocol), ICMP (Internet Control Message Protocol), and IGMP (Internet Group Management Protocol).
- Transport Layer: Provides end-to-end communication between applications. The primary protocols are TCP (Transmission Control Protocol) and UDP (User Datagram Protocol).
- Application Layer: Handles application-specific data formats and protocols, such as HTTP, FTP, and DNS.
Understand algorithm characteristics and complexity
An algorithm is a defined set of steps to perform a specific task. To be valid, an algorithm must possess five characteristics:
- Input: Zero or more inputs.
- Output: At least one output.
- Finiteness: Must terminate after a finite number of steps.
- Definiteness: Each step must be unambiguous.
- Feasibility: Each step must be executable within a finite amount of time.
Algorithm efficiency is evaluated using two metrics:
- Time Complexity: The amount of time required to execute the program (processor usage).
- Space Complexity: The amount of memory required to execute the program.
In most contexts, "complexity" refers specifically to the worst-case time complexity.
Handle object destruction with __del__
The__del__()method is similar to a destructor in C# and is called when an object is about to be destroyed. In Python, this typically happens when the object's reference count reaches zero and it is collected by the Garbage Collector (GC).class Person(object): def __del__(self): print("Object destroyed") p1 = Person() p2 = p1 del p1 # Reference count still > 0 del p2 # Reference count becomes 0, __del__ is calledOrganize modules into packages
A package is a directory containing modules. To treat a directory as a package, include an__init__.pyfile. While optional in Python 3,__init__.pyis used to control package import behavior and is executed when the package is first imported.my_project/ ├── my_package/ │ ├── __init__.py │ ├── module1.py │ └── module2.py └── setup.pyUnderstand Tree data structure fundamentals
A tree is an abstract data type (ADT) consisting of $n$ ($n \ge 1$) finite nodes in a hierarchical relationship. Key characteristics include:
- Each node can have zero or more child nodes.
- The node without a parent is the root node.
- Every non-root node has exactly one parent.
- Except for the root, each child node can be divided into multiple disjoint subtrees.
Relationship between Data Structures and Algorithms
Data structures provide a static description of the relationships between data elements. To create efficient programs, algorithms must be designed and selected based on these structures. The fundamental relationship is expressed as: Program = Data Structure + Algorithm. In this context, the data structure serves as the carrier for the problem that the algorithm is designed to solve.Understand class objects in Python
In Python, everything is an object, including classes. A class is an object that possesses the ability to create instances of itself. Class attributes and class methods are essentially members of the class object. The process of defining a class using theclasskeyword automatically creates this class object.class Test(object): pass Test1 = Test # Assign class object to a variable Test.name = "Test class" # Extend a class attribute print(Test) # Print the class objectUnderstand Linked List fundamentals and time complexity
A linked list is a non-contiguous storage structure where logical order is maintained via pointers. Each node consists of a data field and a pointer field to the next node. Unlike sequential lists, linked lists do not support index-based access and require sequential traversal to locate elements.
Time Complexity:
- Head Insertion:
O(1) - Tail Insertion / Position-based Insertion:
O(n) - Deletion:
O(n) - Modification:
O(n) - Query:
O(n)
- Head Insertion:
Understand Python Coroutines and their use cases
Coroutines (also known as micro-threads or fibers) are execution units smaller than threads. They maintain their own CPU context, allowing a program to switch between execution points while preserving the state. Unlike OS threads, coroutine switching is handled in user-space (typically 1:N mapping where one thread contains multiple coroutines), making it more efficient as it avoids heavy OS kernel overhead.
Key Usage Guidelines:
- IO-Bound Tasks: Coroutines are highly recommended for IO-intensive applications (e.g., network requests, file reading) where the program would otherwise wait for data.
- CPU-Bound Tasks: Coroutines are NOT suitable for CPU-intensive tasks because the scheduler is typically passive; a CPU-heavy coroutine will not yield control, preventing other coroutines from executing. Use multi-processing for CPU-intensive tasks to utilize multi-core performance.
Understand Python's Reference Counting mechanism
Python uses reference counting as its primary garbage collection mechanism. Every object in CPython is based on the
PyObjectstruct, which containsob_refcntto track how many references point to the object. Whenob_refcntreaches zero, the object is immediately reclaimed.Reference count increases (+1) when:
- An object is created (e.g.,
a = 23) - An object is referenced by another variable (e.g.,
b = a) - An object is passed as an argument to a function
- An object is stored in a container (e.g.,
list1 = [a, a])
Reference count decreases (-1) when:
- A reference is explicitly destroyed using
del - A reference is assigned to a new object (e.g.,
a = 24) - A local variable goes out of scope after a function returns
- A container holding the object is destroyed or the object is removed from the container.
- An object is created (e.g.,