Master Core Python, Database, Linux, and Networking Concepts in One Guide
This comprehensive guide covers essential programming fundamentals—including Python memory management, metaclasses, decorators, multithreading, data structures, algorithmic techniques, database concepts such as ACID, indexing, and transaction isolation, Redis operations, Linux memory handling, networking protocols, Docker/Kubernetes commands, and core testing methodologies—providing clear explanations and practical code examples.
Python Fundamentals
Garbage Collection Mechanism
Python uses reference counting combined with a generational mark‑and‑sweep collector. Each object has a reference counter; when it drops to zero the object is reclaimed. Cyclic references are detected by the mark‑and‑sweep phase, which periodically scans reachable objects and frees those that are not marked. Python also employs generational collection to improve efficiency.
Metaclasses
A metaclass is a class that creates other classes. By default Python uses the built‑in type metaclass. Custom metaclasses can override class creation by defining __new__ or __init__. Example:
class MyMeta(type):
def __new__(cls, name, bases, attrs):
print(f'Creating class {name}')
return super().__new__(cls, name, bases, attrs)
class MyClass(metaclass=MyMeta):
pass
# Output: Creating class MyClassDecorators
Decorators are syntactic sugar that wrap a function or class with additional behavior without modifying the original code. They rely on closures: the decorator returns a new wrapper function that calls the original function.
def my_decorator(func):
def wrapper(*args, **kwargs):
print('Before call')
result = func(*args, **kwargs)
print('After call')
return result
return wrapper
@my_decorator
def my_function():
print('In function')
my_function()
# Output:
# Before call
# In function
# After callMultithreading
Python’s threading module provides a simple way to run code concurrently. A Thread object is created with a target function and started with start(). Because of the Global Interpreter Lock (GIL), true parallelism is limited; for CPU‑bound work consider multiprocessing or thread pools.
import threading
def thread_function(name):
print(f'Thread {name}: Starting...')
for i in range(10):
print(f'Thread {name}: {i}')
print(f'Thread {name}: Finishing...')
threads = []
for i in range(5):
t = threading.Thread(target=thread_function, args=(i,))
threads.append(t)
t.start()
for t in threads:
t.join()Python vs. Java
Python is dynamically typed, uses automatic memory management, and generally runs slower than Java, which is statically typed, compiled to bytecode, and has faster execution. Python excels in rapid development, data analysis, and scripting, while Java dominates enterprise and Android development.
Mutable vs. Immutable Objects
Immutable objects (e.g., integers, strings, tuples) cannot be altered after creation; mutable objects (e.g., lists, dictionaries) can. Immutability enables safe sharing and efficient reference counting, whereas mutability allows in‑place updates.
a = 5 # immutable
a = a + 1 # creates a new int
b = "hello" # immutable
# b[0] = 'x' # error
c = [1, 2, 3] # mutable
c[0] = 4 # modifies in place
d = (1, 2, 3) # immutable tuple
# d[0] = 4 # errorFunctional Programming
Python supports functional concepts such as higher‑order functions ( map, filter), anonymous functions ( lambda), built‑in functional utilities ( reduce), list comprehensions, and modules like functools and itertools. Generators provide lazy evaluation.
Closures
A closure is a nested function that captures variables from its enclosing scope, allowing the inner function to access those variables even after the outer function has finished.
def outer_func(x):
y = 2 * x
def inner_func():
return y * x
return inner_func
add_3 = outer_func(3)
print(add_3()) # 6Generators and Iterators
Generators are special functions that yield values one at a time, implementing the iterator protocol. Example of a Fibonacci generator:
def fibonacci(n):
a, b = 0, 1
while True:
if n <= 0:
raise StopIteration
yield a
a, b = b, a + b
for i in fibonacci(10):
print(i)Data Structures and Algorithms
Hash Table Implementation
Python’s built‑in dict is a hash table. A simple custom implementation demonstrates the basic operations.
class HashTable:
def __init__(self):
self.size = 10000
self.buckets = [None] * self.size
def hash(self, key):
return key % self.size
def set(self, key, value):
index = self.hash(key)
if not self.buckets[index]:
self.buckets[index] = [(key, value)]
else:
for pair in self.buckets[index]:
if pair[0] == key:
pair[1] = value
break
else:
self.buckets[index].append((key, value))
def get(self, key):
index = self.hash(key)
if self.buckets[index]:
for k, v in self.buckets[index]:
if k == key:
return v
return None
def delete(self, key):
index = self.hash(key)
if self.buckets[index]:
for i, (k, _) in enumerate(self.buckets[index]):
if k == key:
del self.buckets[index][i]
return True
return FalseTuring‑Complete Language
A language is Turing‑complete if it can simulate a universal Turing machine. Python possesses loops, conditionals, and recursion, making it Turing‑complete.
Greatest Common Divisor (Euclidean Algorithm)
The Euclidean algorithm repeatedly applies the remainder operation to find the GCD of two or more integers.
def gcd(a: int, b: int) -> int:
"""Return the greatest common divisor of a and b."""
while b != 0:
a, b = b, a % b
return abs(a)
def gcd(*nums: int) -> int:
"""Return the GCD of a sequence of numbers."""
g = nums[0]
for n in nums[1:]:
g = gcd(g, n)
return g
print(gcd(48, 28, 18)) # 6Database Fundamentals (MySQL & Redis)
MySQL ACID Properties
Atomicity, Consistency, Isolation, and Durability ensure reliable transactions. MySQL supports configurable isolation levels such as READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, and SERIALIZABLE.
MySQL Storage Engines
InnoDB (default, transactional, row‑level locking), MyISAM (fast reads, no transactions), MEMORY (in‑memory tables), NDB Cluster (distributed), Archive (log storage), MariaDB Galera (strong consistency), TokuDB (compression).
SQL Optimization Techniques
Use appropriate indexes.
Reduce query count via joins.
Cache frequent results.
Partition large tables.
Write precise WHERE clauses.
Keep statistics up‑to‑date.
Index Working Principle
Indexes are typically B+‑tree structures that map key values to row locations, allowing logarithmic‑time lookups similar to a book’s table of contents.
Transaction Isolation Levels
READ UNCOMMITTED (allows dirty reads), READ COMMITTED (prevents dirty reads), REPEATABLE READ (prevents non‑repeatable reads), SERIALIZABLE (full isolation).
Primary Key, Foreign Key, Unique Constraint
Primary keys uniquely identify rows and cannot be NULL. Foreign keys enforce referential integrity between tables. Unique constraints guarantee column‑level uniqueness but may allow NULL.
Performance Bottleneck Analysis via Logs
Examine system logs, slow‑query logs, error logs, and statistics to identify long‑running queries, deadlocks, or resource contention.
Slow Query Optimization
Use EXPLAIN to inspect execution plans, add or adjust indexes, rewrite queries, or consider caching.
Redis Core Features
Redis is an in‑memory key‑value store supporting strings, hashes, lists, sets, sorted sets, persistence (RDB/AOF), pub/sub, and distributed locking.
Redis Data Structures
String
List
Set
Sorted Set
Hash
Redis Persistence
RDB snapshots the dataset at intervals; AOF logs every write operation for more durable recovery.
Redis Expiration Strategies
Time‑based TTL per key, memory‑based eviction policies (e.g., LRU), or hybrid approaches.
Distributed Lock with Redis
Use SETNX to acquire a lock and DEL to release it; Lua scripts can make the operation atomic.
Redis Cluster Architecture
Masters store data, slaves replicate masters for reads, and Sentinel monitors nodes and performs failover. The cluster uses hash slots for sharding and supports dynamic scaling.
Cache Avalanche Mitigation
Redundant backup caches.
Staggered TTLs.
Proactive refresh of hot keys.
LRU eviction.
Operating System & Networking
Linux Memory Management
Linux uses a multi‑level page table per process, paging, and swap space. It also employs free‑list management and various page‑replacement algorithms.
Common grep Options
-c: count matching lines -v: invert match -n: show line numbers -i: ignore case -E: extended regex -o: show only matched part -q: quiet mode -F: fixed‑string pattern
Docker Command Cheat Sheet
docker run: start a new container docker images: list images docker ps: list running containers docker rm: remove containers docker rmi: remove images docker build: build an image docker pull: pull an image docker push: push an image docker network: manage networks docker volume: manage volumes docker exec: run a command in a container
Kubernetes Command Cheat Sheet
kubectl apply: apply a configuration file kubectl create: create a resource kubectl delete: delete a resource kubectl describe: describe resources kubectl rollout: roll out or rollback kubectl scale: scale replicas kubectl logs: view logs kubectl get: get resources kubectl top: show CPU/memory usage kubectl config: configure kubectl kubectl cordon: mark node unschedulable kubectl drain: safely evict pods
TCP/IP Stack Overview
Four layers: Application (HTTP, FTP, SMTP), Transport (TCP, UDP), Internet (IP), Link (ARP, ICMP).
DNS Server Operation
Distributed hierarchical system that resolves domain names to IP addresses using recursive and iterative queries, with caching at each level.
HTTP Status Codes
200 OK
301 Moved Permanently
302 Found
400 Bad Request
403 Forbidden
404 Not Found
500 Internal Server Error
HTTP vs. HTTPS
HTTPS adds an SSL/TLS layer to encrypt traffic, providing confidentiality and integrity over plain HTTP.
TCP Three‑Way Handshake and Four‑Way Teardown
Handshake: SYN → SYN‑ACK → ACK. Teardown: FIN → ACK → FIN → ACK, followed by TIME_WAIT.
Testing and Interview Topics
Black‑Box vs. White‑Box Testing
Black‑box focuses on external functionality without knowledge of internal code; white‑box examines internal logic, paths, and security.
Using unittest for Unit Tests
Define a subclass of unittest.TestCase, write test methods prefixed with test_, and run via unittest.main().
Code Coverage Metrics
Measure how much of the source code is exercised by tests: line coverage, branch coverage, and path coverage.
Typical Interview Questions (Behavioral & Project)
Examples include describing testing design in a past project, discussing a serious bug you fixed, handling conflicting priorities, and resolving team disagreements.
Advanced Python Topics
Multiple Inheritance
Python allows a class to inherit from multiple base classes, offering flexibility but risking name collisions and complexity.
Private Variables
Prefixing an attribute with double underscores triggers name mangling (e.g., __var) to discourage external access; properties can provide controlled access.
Algorithmic Examples
Hash Table Complexity
Average‑case operations are O(1); worst‑case (many collisions) degrades to O(n).
Binary Search Tree Characteristics
Each node’s left subtree contains smaller keys, right subtree larger keys, enabling O(log n) search, insertion, and deletion on balanced trees.
Quick Sort in Python
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
