A Word About Names and Objects
In Python, objects have individuality, and multiple names can be bound to the same object (aliasing):This is important for mutable objects like lists and dictionaries. For immutable types (numbers, strings, tuples), aliasing doesn’t affect program behavior.
Python Scopes and Namespaces
A namespace is a mapping from names to objects. Examples include:- Built-in names (functions like
abs(), exception names) - Global names in a module
- Local names in a function
- Attributes of an object
Scope Example
A First Look at Classes
Class Definition Syntax
The simplest class definition:Class Objects
Classes support two operations: attribute references and instantiation.The init Method
Customize instance creation with__init__():
Instance Objects
Instances understand two kinds of attributes:- Data attributes (instance variables)
- Methods (functions that belong to the object)
Method Objects
Methods are called on instances:Class and Instance Variables
Class variables are shared by all instances:Inheritance
Derive new classes from existing ones:Calling Base Class Methods
Built-in Functions for Inheritance
isinstance(): Check an instance’s type:Multiple Inheritance
Python supports multiple base classes:Private Variables
Python has no true private variables, but there’s a convention: Single underscore (_spam): Internal implementation detail
__spam): Avoid name clashes in subclasses
Name mangling replaces
__spam with _classname__spam to avoid conflicts.Iterators
Make your classes iterable:Generators
Generators are a simple way to create iterators:__iter__()and__next__()are created automatically- Local variables and execution state are saved between calls
- Automatically raise
StopIterationwhen done
Generator Expressions
Like list comprehensions but with parentheses:Dataclasses
Usedataclasses for simple data containers:
Best Practices
Use self
Always use
self as the first parameter name for instance methodsDocument Classes
Use docstrings to document class purpose and usage
Favor Composition
Prefer composition over inheritance when possible
Keep It Simple
Don’t over-engineer - start simple and refactor as needed
Summary
You’ve completed the Python tutorial! You now understand:- Classes and objects
- Inheritance and polymorphism
- Special methods and protocols
- Iterators and generators
- Modern Python features like dataclasses
- The Python Standard Library
- Advanced topics like decorators, context managers, and metaclasses
- Real-world projects and contributions to open source
