Fundamentals 14 min read

Master Python Basics: From Variables to Advanced OOP Techniques

This comprehensive guide walks experienced developers through Python fundamentals—including data types, control flow, functions, advanced features like generators and decorators, object‑oriented programming, modules, and debugging—providing concise examples and practical code snippets to deepen their expertise.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python Basics: From Variables to Advanced OOP Techniques

This article, originally shared by a Python training class, presents a concise yet thorough overview of Python programming aimed at developers with some experience.

Simple Input and Output

Output example: print 10, '十' Input example: name = raw_input()

Python Basics

Data Types and Variables

Common types: integer, float, string (enclosed in single or double quotes), boolean (True, False). Escape characters use backslash (\). Multi‑line strings use triple quotes '''...'''. Boolean operators: and, or, not. Null value: None. Python has no true constants; by convention, constants are written in all caps.

Strings and Encoding

String formatting examples: 'hello, %s' % 'world!' Use %s as a placeholder and provide a tuple of values.

Using Lists and Tuples

List example (array): ['1', 'hello'] Get length with len(list) . Tuple example (immutable array): (1, 2, 3)

Conditional Statements and Loops

if condition: block elif condition: block else: block (indentation is mandatory). for item in list: block range(number) generates a list from 0 to number‑1. while condition: block Convert strings to numbers with int('string') or float('string') .

Using dict and set

Dictionary example: dict = {'key': value} Access with dict.get(key) to avoid KeyError; returns None if missing. Remove an item with dict.pop(key) . Set provides unique elements and supports union (|), intersection (&), difference (-), and symmetric difference (^).

Functions

Defining Functions

Empty function: def func(): pass Type checking with isinstance(var, (type1, type2)) . Return multiple values via a tuple, e.g., x, y = 3, 4 . Default arguments must appear after non‑default ones: def method(arg1='arg1'): Variable‑length positional arguments: def method(*var_arg): Keyword arguments: def method(**kw): Combined signature example: def func(a, b, c=0, *args, **kw): func(*args, **kw) Recursive functions can cause stack overflow; Python does not optimize tail recursion.

Advanced Features

Slicing

array[0:3] – elements 0,1,2 (3 items). array[-3:-1] – third‑last to second‑last element. array[::5] – every fifth element. Strings support the same slicing syntax.

Iteration

Iterate with for item in array ; array can be a list, dict, or string. Check iterability with isinstance(obj, Iterable) . Iterate over a dict: for key in dict: ... for value in dict.itervalues(): ... for k, v in dict.iteritems(): ...

List Comprehensions

Basic form: [x * x for x in range(1, 10) if x % 2 == 0] Nested loops: [x * y for x in range(1, 10) for y in range(20, 30)]

Generators

Use generators to produce large sequences lazily. Convert a list comprehension to a generator by replacing [] with () . Define a generator function with yield : def gen(): yield item ...

Functional Programming

Higher‑Order Functions

Functions can be passed as arguments and returned as values. map, reduce, filter, and sorted are common higher‑order utilities.

Returning Functions

Define a function inside another and return it; closures retain access to the outer scope.

Anonymous Functions

Lambda syntax: lambda args: expression .

Decorators

Decorators add pre‑ and post‑logic to functions. def log(func): @functools.wraps(func) def wrapper(*args, **kw): print('call %s():' % func.__name__) return func(*args, **kw) return wrapper @log def now(): print('2013-12-25')

Partial Functions

Use functools.partial to fix certain arguments of a function. int2 = functools.partial(int, base=2) Useful for simplifying calls with many parameters.

Modules

Modules

A .py file is a module; a directory is a package.

Using Modules

Standard module template example: #!/usr/bin/env python # -*- coding: utf-8 -*- """a test module""" __author__ = 'Michael Liao' import sys def test(): args = sys.argv if len(args) == 1: print('Hello, world!') elif len(args) == 2: print('Hello, %s!' % args[1]) else: print('Too many arguments!') if __name__ == '__main__': test() Private module members start with an underscore.

Installing Third‑Party Modules

Use pip install package_name .

Using __future__

The future import enables features from upcoming Python versions.

Object‑Oriented Programming

Classes and Instances

Define a class: class ClassName(SuperClass): pass Constructor: def __init__(self, args): ...

Access Restrictions

Names starting with double underscores become name‑mangled (pseudo‑private). Use getters/setters for controlled access.

Inheritance and Polymorphism

Specify a parent class in the class definition; override methods to achieve polymorphism.

Getting Object Information

Use type() to get the type, isinstance() for inheritance checks, and dir() to list attributes and methods.

Advanced OOP

Using __slots__

Define __slots__ = ('allowed_attr',) to restrict dynamic attribute creation and save memory.

Using @property

Define a managed attribute with getter and setter: @property def score(self): return self._score @score.setter def score(self, value): if not isinstance(value, int): raise ValueError('score must be an integer!') if value < 0 or value > 100: raise ValueError('score must be between 0 and 100!') self._score = value

Multiple Inheritance

Prefer mixins over deep multiple inheritance; mixins provide reusable functionality.

Customizing Classes

Special methods allow fine‑grained control: __str__ – human‑readable representation. __repr__ – unambiguous representation. __iter__ and __next__ – iteration support. __getitem__ – index access. __getattr__ – fallback attribute lookup. __call__ – make instances callable. Use callable(obj) to test callability.

Using Metaclasses

Dynamic class creation via type('ClassName', (BaseClass,), dict(methodName=method)) .

Errors, Debugging, and Testing

Errors

Use try...except...finally blocks; the base class for exceptions is BaseException . Log exceptions with the logging module: logging.exception(e) . Define custom exceptions by subclassing Exception and raise them with raise MyError('msg') .

Debugging

Assertions: assert condition, 'error message' . Use the logging module for various log levels (debug, info, warning, error). Set log level with logging.basicConfig(level=logging.INFO) . Interactive debugging with python -m pdb script.py or inserting import pdb; pdb.set_trace() . IDE recommendation: PyCharm.

The above summarizes the author’s Python knowledge; readers are encouraged to like, comment, and discuss.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonOOPModules
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.