Learning Python. 6th Edition - Helion

ISBN: 9781098171261
stron: 1172, Format: ebook
Data wydania: 2025-02-25
Księgarnia: Helion
Cena książki: 237,15 zł (poprzednio: 275,76 zł)
Oszczędzasz: 14% (-38,61 zł)
Get a comprehensive, in-depth introduction to the core Python language with this hands-on book. Based on author Mark Lutz's popular training course, this updated sixth edition will help you quickly write efficient, high-quality code with Python. It's an ideal way to begin, whether you're new to programming or a professional developer versed in other languages.
Complete with quizzes, exercises, and helpful illustrations, this easy-to-follow self-paced tutorial gets you started with Python 3.12 and all other releases in use today. With a pragmatic focus on what you need to know, it also introduces some advanced language features that have become increasingly common in Python code.
This book helps you:
- Explore Python's built-in object types such as strings, lists, dictionaries, and files
- Create and process objects with Python statements, and learn Python's syntax model
- Use functions and functional programming to avoid redundancy and maximize reuse
- Organize code into larger components with modules and packages
- Code robust programs with Python's exception handling and development tools
- Apply object-oriented programming and classes to make code customizable
- Survey advanced Python tools including decorators, descriptors, and metaclasses
- Write idiomatic Python code that runs portably across a wide variety of platforms
Osoby które kupowały "Learning Python. 6th Edition", wybierały także:
- Biologika Sukcesji Pokoleniowej. Sezon 3. Konflikty na terytorium 117,27 zł, (12,90 zł -89%)
- Windows Media Center. Domowe centrum rozrywki 66,67 zł, (8,00 zł -88%)
- Podręcznik startupu. Budowa wielkiej firmy krok po kroku 92,14 zł, (12,90 zł -86%)
- Ruby on Rails. Ćwiczenia 18,75 zł, (3,00 zł -84%)
- Prawa ludzkiej natury 75,88 zł, (12,90 zł -83%)
Spis treści
Learning Python. 6th Edition eBook -- spis treści
- Preface
- Python
- This Book
- This Edition
- Media Choices
- Updates and Examples
- Conventions and Reuse
- Acknowledgments
- I. Getting Started
- 1. A Python Q&A Session
- Why Do People Use Python?
- Software Quality
- Developer Productivity
- Is Python a Scripting Language?
- OK, but Whats the Downside?
- Who Uses Python Today?
- What Can I Do with Python?
- Systems Programming
- GUIs and UIs
- Internet and Web Scripting
- Component Integration
- Database Access
- Rapid Prototyping
- Numeric and Scientific Programming
- And More: AI, Games, Images, QA, Excel, Apps
- What Are Pythons Technical Strengths?
- Its Object-Oriented and Functional
- Its Free and Open
- Its Portable
- Its Powerful
- Its Mixable
- Its Relatively Easy to Use
- Its Relatively Easy to Learn
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- Why Do People Use Python?
- 2. How Python Runs Programs
- Introducing the Python Interpreter
- Program Execution
- The Programmers View
- Pythons View
- Bytecode compilation
- The Python Virtual Machine (PVM)
- Performance implications
- Development implications
- Execution-Model Variations
- Python Implementation Alternatives
- Standalone Executables
- Future Possibilities
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- 3. How You Run Programs
- Installing Python
- Interactive Code
- Starting an Interactive REPL
- Where to Run: Code Folders
- What Not to Type: Prompts and Comments
- Other Python REPLs
- Running Code Interactively
- Why the Interactive Prompt?
- Learning
- Testing
- Program Files
- A First Script
- Running Files with Command Lines
- Command-Line Usage Variations
- Other Ways to Run Files
- Clicking and Tapping File Icons
- The IDLE Graphical User Interface
- Other IDEs for Python
- Smartphone Apps
- WebAssembly for Browsers
- Jupyter Notebooks for Science
- Ahead-of-Time Compilers for Speed
- Running Code in Code
- Importing modules
- Reloading modules
- Module attributes: a first look
- The exec built-in
- Command-line launchers
- Other Launch Options
- Which Option Should I Use?
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- Test Your Knowledge: Part I Exercises
- II. Objects and Operations
- 4. Introducing Python Objects
- The Python Conceptual Hierarchy
- Why Use Built-in Objects?
- Pythons Core Object Types
- Numbers
- Strings
- Sequence Operations
- Immutability
- Type-Specific Methods
- Getting Help
- Other Ways to Code Strings
- Unicode Strings
- Lists
- Sequence Operations
- Type-Specific Operations
- Bounds Checking
- Nesting
- Comprehensions
- Dictionaries
- Mapping Operations
- Nesting Revisited
- Missing Keys: if Tests
- Item Iteration: for Loops
- Tuples
- Why Tuples?
- Files
- Unicode and Byte Files
- Other File-Like Tools
- Other Object Types
- Sets
- Booleans and None
- Types
- Type Hinting
- User-Defined Objects
- And Everything Else
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- 5. Numbers and Expressions
- Numeric Object Basics
- Numeric Literals
- Built-in Numeric Tools
- Python Expression Operators
- Mixed Operators: Precedence
- Parentheses Group Subexpressions
- Mixed Types Are Converted Up
- Preview: Operator Overloading and Polymorphism
- Numbers in Action
- Variables and Basic Expressions
- Numeric Display Formats
- Comparison Operators
- Chained comparisons
- Floating-point equality
- Division Operators
- Floor versus truncation
- Integer Precision
- Complex Numbers
- Hex, Octal, and Binary
- Bitwise Operations
- Underscore Separators in Numbers
- Other Built-in Numeric Tools
- Other Numeric Objects
- Decimal Objects
- Decimal basics
- Setting decimal precision
- Fraction Objects
- Fraction basics
- Numeric accuracy in fractions and decimals
- Set Objects
- Sets in action
- Immutable constraints and frozen sets
- Set comprehensions
- Why sets?
- Boolean Objects
- Decimal Objects
- Numeric Extensions
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- Numeric Object Basics
- 6. The Dynamic Typing Interlude
- The Case of the Missing Declaration Statements
- Variables, Objects, and References
- Types Live with Objects, Not Variables
- Objects Are Garbage-Collected
- Shared References
- Shared References and In-Place Changes
- Shared References and Equality
- Dynamic Typing Is Everywhere
- Type Hinting: Optional, Unused, and Why?
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- The Case of the Missing Declaration Statements
- 7. String Fundamentals
- String Object Basics
- String Literals
- Single and Double Quotes Are the Same
- Escape Sequences Are Special Characters
- Raw Strings Suppress Escapes
- Triple Quotes and Multiline Strings
- Strings in Action
- Basic Operations
- Indexing and Slicing
- Extended slicing: The third limit and slice objects
- String Conversion Tools
- Character-code conversions
- String comparisons
- Changing Strings Part 1: Sequence Operations
- String Methods
- Method Call Syntax
- All String Methods (Today)
- Changing Strings, Part 2: String Methods
- More String Methods: Parsing Text
- Other Common String Methods
- String Formatting: The Triathlon
- String-Formatting Options
- The String-Formatting Expression
- Formatting expression basics
- Formatting expression custom formats
- Advanced formatting expression examples
- Dictionary-based formatting expressions
- The String-Formatting Method
- Formatting method basics
- Adding keys, attributes, and offsets
- Formatting method custom formats
- Advanced formatting method examples
- The F-String Formatting Literal
- F-string formatting basics
- F-string custom formats
- Advanced f-string examples
- And the Winner Is
- General Type Categories
- Types Share Operation Sets by Categories
- Mutable Types Can Be Changed in Place
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- 8. Lists and Dictionaries
- Lists
- Lists in Action
- Basic List Operations
- Indexing and Slicing
- Changing Lists in Place
- Index and slice assignments
- List method calls
- Sorting lists
- More List Methods
- Iteration, Comprehensions, and Unpacking
- List comprehensions and maps
- List-literal unpacking
- Other List Operations
- Dictionaries
- Dictionaries in Action
- Basic Dictionary Operations
- Changing Dictionaries in Place
- More Dictionary Methods
- Other Dictionary Makers
- Dictionary-literal unpacking
- Dictionary Comprehensions
- Key Insertion Ordering
- Dictionary Union Operator
- Intermission: Books Database
- Mapping values to keys
- Dictionary Usage Tips
- Using dictionaries to simulate flexible lists: Integer keys
- Using dictionaries for sparse data structures: Tuple keys
- Avoiding missing-key errors
- Nesting in dictionaries
- Dictionary key/value/item view objects
- Dictionary views and sets
- Sorting dictionary keys
- Dictionary magnitude comparisons
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- 9. Tuples, Files, and Everything Else
- Tuples
- Tuples in Action
- Tuple syntax peculiarities: Commas and parentheses
- Conversions, methods, and immutability
- Why Lists and Tuples?
- Records Revisited: Named Tuples
- Tuples in Action
- Files
- Opening Files
- Using Files
- Files in Action
- Text and Binary Files: The Short Story
- Storing Objects with Conversions
- Storing Objects with pickle
- Storing Objects with JSON
- Storing Objects with Other Tools
- File Context Managers
- Other File Tools
- Core Types Review and Summary
- Object Flexibility
- References Versus Copies
- Comparisons, Equality, and Truth
- Mixed-type comparisons and sorts
- Dictionary comparisons
- The Meaning of True and False in Python
- The None object
- The bool type
- Pythons Type Hierarchies
- Type Objects
- Other Types in Python
- Built-in Type Gotchas
- Assignment Creates References, Not Copies
- Repetition Adds One Level Deep
- Beware of Cyclic Data Structures
- Immutable Types Cant Be Changed in Place
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- Test Your Knowledge: Part II Exercises
- Tuples
- III. Statements and Syntax
- 10. Introducing Python Statements
- The Python Conceptual Hierarchy Revisited
- Pythons Statements
- A Tale of Two ifs
- What Python Adds
- What Python Removes
- Parentheses are optional
- End-of-line is end of statement
- End of indentation is end of block
- Why Indentation Syntax?
- A Few Special Cases
- Statement rule special cases
- Block rule special case
- A Quick Example: Interactive Loops
- A Simple Interactive Loop
- Doing Math on User Inputs
- Handling Errors by Testing Inputs
- Handling Errors with try Statements
- Supporting Floating-Point Numbers
- Nesting Code Three Levels Deep
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- 11. Assignments, Expressions, and Prints
- Assignments
- Assignment Syntax Forms
- Basic Assignments
- Sequence Assignments
- Advanced sequence-assignment patterns
- Extended-Unpacking Assignments
- Extended unpacking in action
- Boundary cases
- A useful convenience
- Application to for loops
- Multiple-Target Assignments
- Multiple-target assignment and shared references
- Augmented Assignments
- Augmented assignment and shared references
- Named Assignment Expressions
- When to use named assignment
- Variable Name Rules
- Naming conventions
- Names have no type, but objects do
- Expression Statements
- Expression Statements and In-Place Changes
- Print Operations
- The print Function
- Call format
- The print function in action
- Print Stream Redirection
- The Python hello world program
- Manual stream redirection
- Automatic stream redirection
- The print Function
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- Assignments
- 12. if and match Selections
- if Statements
- General Format
- Basic Examples
- Multiple-Choice Selections
- Handling switch defaults
- Handling larger actions
- match Statements
- Basic match Usage
- Match versus if live
- Advanced match Usage
- Basic match Usage
- Python Syntax Revisited
- Block Delimiters: Indentation Rules
- Avoid mixing tabs and spaces
- Statement Delimiters: Lines and Continuations
- Special Syntax Cases in Action
- Block Delimiters: Indentation Rules
- Truth Values Revisited
- The if/else Ternary Expression
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- if Statements
- 13. while and for Loops
- while Loops
- General Format
- Examples
- break, continue, pass, and the Loop else
- General Loop Format
- pass
- The ellipsis-literal alternative
- continue
- The nested-code alternative
- break
- The named-assignment alternative
- Loop else
- Why the loop else?
- for Loops
- General Format
- Examples
- Basic usage
- Other data types
- Tuple (sequence) assignment in for loops
- Extended-unpacking assignment in for loops
- Nested for loops
- Loop Coding Techniques
- Counter Loops: range
- Sequence Scans: while, range, and for
- Sequence Shufflers: range and len
- Skipping Items: range and Slices
- Changing Lists: range and Comprehensions
- Parallel Traversals: zip
- More on zip: size and truncation
- More zip roles: dictionaries
- Offsets and Items: enumerate
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- while Loops
- 14. Iterations and Comprehensions
- Iterations
- The Iteration Protocol
- The iter and next built-ins
- The full iteration protocol
- Manual iteration
- More on iter and next
- Other Built-in Iterables
- Reprise: Dictionaries, range, enumerate, and zip
- Iterator nesting
- Functional iterables: map and filter
- Multiple-pass versus single-pass iterables
- Standard-library iterables in Python
- The Iteration Protocol
- Comprehensions
- List Comprehension Basics
- List Comprehensions and Files
- Extended List Comprehension Syntax
- Filter clauses: if
- Nested loops: for
- Comprehensions Cliff-Hanger
- Iteration Tools
- Other Iteration Topics
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- Iterations
- 15. The Documentation Interlude
- Python Documentation Sources
- # Comments
- The dir Function
- Docstrings and __doc__
- User-defined docstrings
- Docstring standards
- Built-in docstrings
- Pydoc: The help Function
- Running help on built-in tools
- Running help on your own code
- Pydoc: HTML Reports
- Using Pydocs browser interface
- Customizing Pydoc
- More Pydoc tips
- Beyond Docstrings: Sphinx
- The Standard Manuals
- Web Resources
- Common Coding Gotchas
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- Test Your Knowledge: Part III Exercises
- Python Documentation Sources
- IV. Functions and Generators
- 16. Function Basics
- Why Use Functions?
- Function Coding Overview
- Basic Function Tools
- Advanced Function Tools
- General Function Concepts
- def Statements
- return Statements
- def Executes at Runtime
- lambda Makes Anonymous Functions
- A First Example: Definitions and Calls
- Definition
- Calls
- Polymorphism in Python
- A Second Example: Intersecting Sequences
- Definition
- Calls
- Polymorphism Revisited
- Segue: Local Variables
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- 17. Scopes
- Python Scopes Basics
- Scopes Overview
- Name Resolution: The LEGB Rule
- Preview: Other Python scopes
- Scopes Examples
- The Built-in Scope
- Redefining built-in names: For better or worse
- The global Statement
- Program Design: Minimize Global Variables
- Program Design: Minimize Cross-File Changes
- Other Ways to Access Globals
- Nested Functions and Scopes
- Nested Scopes Overview
- Nested Scopes Examples
- Closures and Factory Functions
- Arbitrary Scope Nesting
- The nonlocal Statement
- nonlocal Basics
- nonlocal in Action
- nonlocal Boundary Cases
- State-Retention Options
- Nonlocals: Changeable, Per-Call, LEGB
- Globals: Changeable but Shared
- Function Attributes: Changeable, Per-Call, Explicit
- Classes: Changeable, Per-Call, OOP
- And the Winner Is
- Scopes and Argument Defaults
- Loops Require Defaults, Not Scopes
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- Python Scopes Basics
- 18. Arguments
- Argument-Passing Basics
- Arguments and Shared References
- Avoiding Mutable Argument Changes
- Simulating Output Parameters and Multiple Results
- Special Argument-Matching Modes
- Argument Matching Overview
- Argument Matching Syntax
- Argument Passing Details
- Keyword and Default Examples
- Keywords
- Defaults
- Combining keywords and defaults
- Arbitrary Arguments Examples
- Definitions: Collecting arguments
- Calls: Unpacking arguments
- Why arbitrary arguments?
- Keyword-Only Arguments
- Why keyword-only arguments?
- Positional-Only Arguments
- Argument Ordering: The Gritty Details
- Definition Ordering
- Formal definition
- Boundary cases
- Calls Ordering
- Formal definition
- Boundary cases
- Perspective
- Definition Ordering
- Example: The min Wakeup Call
- Full Credit
- Bonus Points
- The Punch Line
- Example: Generalized Set Functions
- Testing the Code
- Example: Rolling Your Own Print
- Using Keyword-Only Arguments
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- Argument-Passing Basics
- 19. Function Odds and Ends
- Function Design Concepts
- Recursive Functions
- Summation with Recursion
- Coding Alternatives
- Loop Statements Versus Recursion
- Handling Arbitrary Structures
- Testing with a separate script
- Recursion versus queues and stacks
- Cycles, paths, and stack limits
- More recursion examples
- Function Tools: Attributes, Annotations, Etc.
- The First-Class Object Model
- Function Introspection
- Function Attributes
- Function Annotations and Decorations
- Function decorators alternative: Preview
- Anonymous Functions: lambda
- lambda Basics
- Why Use lambda?
- Multiway branches: The finale
- How (Not) to Obfuscate Your Python Code
- Scopes: lambdas Can Be Nested Too
- Functional Programming Tools
- Mapping Functions over Iterables: map
- Selecting Items in Iterables: filter
- Combining Items in Iterables: reduce
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- 20. Comprehensions and Generations
- Comprehensions: The Final Act
- List Comprehensions Review
- Formal Comprehension Syntax
- Example: List Comprehensions and Matrixes
- When not to use list comprehensions: Code obfuscation
- When to use list comprehensions: Speed, conciseness, etc.
- Generator Functions and Expressions
- Generator Functions: yield Versus return
- State suspension
- Iteration protocol integration
- Generator functions in action
- Why generator functions?
- Extended generator function protocol: send versus next
- The yield from extension
- Generator Expressions: Iterables Meet Comprehensions
- Why generator expressions?
- Generator expressions versus map
- Generator expressions versus filter
- Generator Functions Versus Generator Expressions
- Generator Odds and Ends
- Generators are single-pass iterables
- Generation in built-ins and classes
- Comprehensions versus type calls and generators
- Scopes and comprehension variables
- Generating infinite (well, indefinite) results
- Generator Functions: yield Versus return
- Example: Shuffling Sequences
- Scrambling Sequences
- Simple functions
- Generator functions
- Generator expressions
- Tester client
- Permutating Sequences
- Why generators here: Space, time, and more
- Scrambling Sequences
- Example: Emulating zip and map
- Coding Your Own map
- Coding Your Own zip and 2.X map
- Asynchronous Functions: The Short Story
- Async Basics
- Running serial tasks with normal blocking calls
- Running concurrent tasks with await and async def
- How not to use async functions
- Running concurrent tasks with as_completed and gather
- Running concurrent tasks with async with and async for
- The Async Wrap-Up
- Async Basics
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- Comprehensions: The Final Act
- 21. The Benchmarking Interlude
- Benchmarking with Homegrown Tools
- Timer Module: Take 1
- Timer Module: Take 2
- Timing Runner and Script
- Iteration Results
- Other Pythons results
- For more good times: Function calls and map
- More Module Mods
- Benchmarking with Pythons timeit
- Basic timeit Usage
- API-calls mode
- Command-line mode
- Handling multiline statements
- Other timeit usage modes
- Timing sort speed
- Automating timeit Benchmarking
- Benchmark module
- Benchmark script
- Timing individual Pythons
- Timing multiple Pythons
- Timing set and dictionary iterations
- Conclusion: Comparing tools
- Basic timeit Usage
- Function Gotchas
- Local Names Are Detected Statically
- Defaults and Mutable Objects
- Functions Without returns
- Miscellaneous Function Gotchas
- Enclosing scopes and loop variables
- Hiding built-ins by assignment
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- Test Your Knowledge: Part IV Exercises
- Benchmarking with Homegrown Tools
- V. Modules and Packages
- 22. Modules: The Big Picture
- Module Essentials
- Why Use Modules?
- Python Program Architecture
- How to Structure a Program
- Imports and Attributes
- Standard-Library Modules
- How Imports Work
- Step 1: Find It
- Step 2: Compile It (Maybe)
- Step 3: Run It
- The Module Search Path
- Search-Path Components
- Configuring the Search Path
- The sys.path List
- Inspecting the module search path
- Changing the module search path
- Module File Selection
- Module sources
- Selection priorities
- Path Outliers: Standalones and Packages
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- 23. Module Coding Basics
- Creating Modules
- Module Filenames
- Other Kinds of Modules
- Using Modules
- The import Statement
- The from Statement
- The from * Statement
- Imports Happen Only Once
- Initialization code
- Imports Are Runtime Assignments
- Changing mutables in modules
- Cross-file name changes
- import and from Equivalence
- Potential Pitfalls of the from Statement
- When import is required
- Module Namespaces
- How Files Generate Namespaces
- Namespace Dictionaries: __dict__
- Attribute Name Qualification
- Imports Versus Scopes
- Namespace Nesting
- Reloading Modules
- reload Basics
- reload Example
- reload Odds and Ends
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- Creating Modules
- 24. Module Packages
- Using Packages
- Package Imports
- Packages and the Module Search Path
- Creating Packages
- Basic Package Structure
- Using the basic package
- Package __init__.py Files
- Using the updated package
- Package __main__.py Files
- Using the updated package
- Basic Package Structure
- Why Packages?
- A Tale of Two Systems
- The Roles of __init__.py Files
- Package-Relative Imports
- Relative and Absolute Imports
- Relative-Import Rationales and Trade-Offs
- Package-Relative Imports in Action
- The normal-import warm-up
- The relative-import adventure
- The absolute-import solution
- Namespace Packages
- Python Import Models
- Namespace-Package Rationales
- The Module Search Algorithm
- Namespace Packages in Action
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- Using Packages
- 25. Module Odds and Ends
- Module Design Concepts
- Data Hiding in Modules
- Minimizing from * Damage: _X and __all__
- Managing Attribute Access: __getattr__ and __dir__
- Enabling Language Changes: __future__
- Dual-Usage Modes: __name__ and __main__
- Example: Unit Tests with __name__
- The as Extension for import and from
- Module Introspection
- Example: Listing Modules with __dict__
- Importing Modules by Name String
- Running Code Strings
- Direct Calls: Two Options
- Example: Transitive Module Reloads
- A recursive reloader
- Testing recursive reloads
- Alternative codings
- Testing reload variants
- Module Gotchas
- Module Name Clashes: Package and Package-Relative Imports
- Statement Order Matters in Top-Level Code
- from Copies Names but Doesnt Link
- from * Can Obscure the Meaning of Variables
- reload May Not Impact from Imports
- reload, from, and Interactive Testing
- Recursive from Imports May Not Work
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- Test Your Knowledge: Part V Exercises
- VI. Classes and OOP
- 26. OOP: The Big Picture
- Why Use Classes?
- OOP from 30,000 Feet
- Attribute Inheritance Search
- Classes and Instances
- Method Calls
- Coding Class Trees
- Operator Overloading
- OOP Is About Code Reuse
- Polymorphism and classes
- Programming by customization
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- 27. Class Coding Basics
- Classes Generate Multiple Instance Objects
- Class Objects Provide Default Behavior
- Instance Objects Are Concrete Items
- A First Example
- Classes Are Customized by Inheritance
- A Second Example
- Classes Are Attributes in Modules
- Classes Can Intercept Python Operators
- A Third Example
- Returning resultsor not
- Other operator-overloading methods
- A Third Example
- The Worlds Simplest Python Class
- Classes: Under the Hood
- Records Revisited: Classes Versus Dictionaries
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- Classes Generate Multiple Instance Objects
- 28. A More Realistic Example
- Step 1: Making Instances
- Coding Constructors
- Testing as You Go
- Using Code Two Ways
- Step 2: Adding Behavior Methods
- Coding Methods
- Step 3: Operator Overloading
- Providing Print Displays
- Step 4: Customizing Behavior by Subclassing
- Coding Subclasses
- Augmenting Methods: The Bad Way
- Augmenting Methods: The Good Way
- Polymorphism in Action
- Inherit, Customize, and Extend
- OOP: The Big Idea
- Step 5: Customizing Constructors, Too
- OOP Is Simpler Than You May Think
- Other Ways to Combine Classes: Composites
- Step 6: Using Introspection Tools
- Special Class Attributes
- A Generic Display Tool
- Instance Versus Class Attributes
- Name Considerations in Tool Classes
- Our Classes Final Form
- Step 7 (Final): Storing Objects in a Database
- Pickles and Shelves
- The pickle module
- The shelve module
- Storing Objects on a shelve Database
- Exploring Shelves Interactively
- Updating Objects on a Shelf
- Pickles and Shelves
- Future Directions
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- Step 1: Making Instances
- 29. Class Coding Details
- The class Statement
- General Syntax and Usage
- Example: Class Attributes
- Methods
- Method Example
- Other Method-Call Possibilities
- Inheritance
- Attribute Tree Construction
- Inheritance Fine Print
- Specializing Inherited Methods
- Class Interface Techniques
- Abstract Superclasses
- Preview: Abstract superclasses with library tools
- Namespaces: The Conclusion
- Simple Names: Global Unless Assigned
- Attribute Names: Object Namespaces
- The Zen of Namespaces: Assignments Classify Names
- Nested Classes: The LEGB Scopes Rule Revisited
- Namespace Dictionaries: Review
- Namespace Links: A Tree Climber
- Documentation Strings Revisited
- Classes Versus Modules
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- The class Statement
- 30. Operator Overloading
- The Basics
- Constructors and Expressions: __init__ and __sub__
- Common Operator-Overloading Methods
- Indexing and Slicing: __getitem__ and __setitem__
- Intercepting Slices
- Intercepting Item Assignments
- But __index__ Means As-Integer
- Index Iteration: __getitem__
- Iterable Objects: __iter__ and __next__
- User-Defined Iterables
- Single versus multiple scans
- Classes versus generators
- Multiple Iterators on One Object
- Classes versus slices
- Coding Alternative: __iter__ Plus yield
- Multiple iterators with yield
- User-Defined Iterables
- Membership: __contains__, __iter__, and __getitem__
- Attribute Access: __getattr__ and __setattr__
- Attribute Reference
- Attribute Assignment and Deletion
- Other Attribute-Management Tools
- Emulating Privacy for Instance Attributes: Part 1
- String Representation: __repr__ and __str__
- Why Two Display Methods?
- Display Usage Notes
- Right-Side and In-Place Ops: __radd__ and __iadd__
- Right-Side Addition
- Reusing __add__ in __radd__
- Propagating class type
- In-Place Addition
- Right-Side Addition
- Call Expressions: __call__
- Function Interfaces and Callback-Based Code
- Comparisons: __lt__, __gt__, and Others
- Boolean Tests: __bool__ and __len__
- Object Destruction: __del__
- Destructor Usage Notes
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- The Basics
- 31. Designing with Classes
- Python and OOP
- Polymorphism Means Interfaces, Not Call Signatures
- OOP and Inheritance: Is-a Relationships
- OOP and Composition: Has-a Relationships
- Stream Processors Revisited
- OOP and Delegation: Like-a Relationships
- Pseudoprivate Class Attributes
- Name Mangling Overview
- Why Use Pseudoprivate Attributes?
- Method Objects: Bound or Not
- Bound Methods in Action
- Classes Are Objects: Generic Object Factories
- Why Factories?
- Multiple Inheritance and the MRO
- How Multiple Inheritance Works
- How the MRO Works
- Attribute Conflict Resolution
- Example: Mix-in Attribute Listers
- Listing instance attributes with __dict__
- Listing inherited attributes with dir
- Listing attributes per object in class trees
- Example: Mapping Attributes to Inheritance Sources
- Other Design-Related Topics
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- Python and OOP
- 32. Class Odds and Ends
- Extending Built-in Object Types
- Extending Types by Embedding
- Extending Types by Subclassing
- The Python Object Model
- Classes Are Types Are Classes
- Some Instances Are More Equal Than Others
- The Inheritance Bifurcation
- The Metaclass/Class Dichotomy
- And One object to Rule Them All
- Advanced Attribute Tools
- Slots: Attribute Declarations
- Slot basics
- You shouldnt normally use slots
- Slots and namespace dictionaries
- Multiple __slot__ lists in superclasses
- Handling slots and other virtual attributes generically
- Slot usage rules
- Example impacts of slots: ListTree and mapattrs
- What about slots speed?
- Properties: Attribute Accessors
- Property basics
- __getattribute__ and Descriptors: Attribute Implementations
- Slots: Attribute Declarations
- Static and Class Methods
- Why the Special Methods?
- Plain-Function Methods
- Static Method Alternatives
- Using Static and Class Methods
- Counting Instances with Static Methods
- Counting Instances with Class Methods
- Counting instances per class with class methods
- Decorators and Metaclasses
- Function Decorator Basics
- A First Look at User-Defined Function Decorators
- A First Look at Class Decorators and Metaclasses
- For More Details
- The super Function
- The super Basics
- The super Details
- A magic proxy
- Attribute-fetch algorithm
- Universal deployment
- Call-chain anchors
- Same argument lists
- Noncalls and operator overloading
- The super Wrap-Up
- Class Gotchas
- Changing Class Attributes Can Have Side Effects
- Changing Mutable Class Attributes Can Have Side Effects, Too
- Multiple Inheritance: Order Matters
- Scopes in Methods and Classes
- Miscellaneous Class Gotchas
- Overwrapping-itis
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- Test Your Knowledge: Part VI Exercises
- Extending Built-in Object Types
- VII. Exceptions
- 33. Exception Basics
- Why Use Exceptions?
- Exception Roles
- Exceptions: The Short Story
- Default Exception Handler
- Catching Exceptions
- Raising Exceptions
- User-Defined Exceptions
- Termination Actions
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- Why Use Exceptions?
- 34. Exception Coding Details
- The try Statement
- try Statement Clauses
- The except and else Clauses
- How try statements work
- Catching many exceptions with a tuple
- Catching all exceptions with empties and Exception
- Catching the no-exception case with else
- Example: Default behavior
- Example: Catching built-in exceptions
- The finally Clause
- Example: Coding termination actions with try/finally
- Combined try Clauses
- Combined-clause syntax rules
- Combining finally and except by nesting
- Combined-clauses example
- The raise Statement
- Raising Exceptions
- The except as hook
- Scopes and except as
- Propagating Exceptions with raise
- Exception Chaining: raise from
- The assert Statement
- Example: Trapping Constraints (but Not Errors!)
- The with Statement and Context Managers
- Basic with Usage
- The Context-Management Protocol
- Multiple Context Managers
- The Termination-Handlers Shoot-Out
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- The try Statement
- 35. Exception Objects
- Exception Classes
- Coding Exceptions Classes
- Why Exception Hierarchies?
- Built-in Exception Classes
- Built-in Exception Categories
- Default Printing and State
- Custom Print Displays
- Custom State and Behavior
- Providing Exception Details
- Providing Exception Methods
- Exception Groups: Yet Another Star!
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- Exception Classes
- 36. Exception Odds and Ends
- Nesting Exception Handlers
- Example: Control-Flow Nesting
- Example: Syntactic Nesting
- Exception Idioms
- Breaking Out of Multiple Nested Loops: go to
- Exceptions Arent Always Errors
- Functions Can Signal Conditions with raise
- Closing Files and Server Connections
- Debugging with Outer try Statements
- Running In-Process Tests
- More on sys.exc_info
- The sys.exception alternativeand diss
- Displaying Errors and Tracebacks
- Exception Design Tips and Gotchas
- What Should Be Wrapped
- Catching Too Much: Avoid Empty except and Exception
- Catching Too Little: Use Class-Based Categories
- Core Language Wrap-Up
- The Python Toolset
- Development Tools for Larger Projects
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- Test Your Knowledge: Part VII Exercises
- Nesting Exception Handlers
- VIII. Advanced Topics
- 37. Unicode and Byte Strings
- Unicode Foundations
- Character Representations
- Character Encodings
- Introducing Python String Tools
- The str Object
- The bytes Object
- The bytearray Object
- Text and Binary Files
- Using Text Strings
- Literals and Basic Properties
- String Type Conversions
- Coding Unicode Strings in Python
- Source-File Encoding Declarations
- Using Byte Strings
- Methods
- Sequence Operations
- Formatting
- Other Ways to Make Bytes
- Mixing String Types
- The bytearray Object
- Using Text and Binary Files
- Text-File Basics
- Text and Binary Modes
- Unicode-Text Files
- Unicode, Bytes, and Other String Tools
- The re Pattern-Matching Module
- The struct Binary-Data Module
- The pickle and json Serialization Modules
- Filenames in open and Other Filename Tools
- The Unicode Twilight Zone
- Dropping the BOM in Python
- Making BOMs in Text Editors
- Making BOMs in Python
- Unicode Normalization: Whither Standard?
- Dropping the BOM in Python
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- Unicode Foundations
- 38. Managed Attributes
- Why Manage Attributes?
- Inserting Code to Run on Attribute Access
- Properties
- The Basics
- A First Example
- Computed Attributes
- Coding Properties with Decorators
- Setter and deleter decorators
- Descriptors
- The Basics
- Descriptor method arguments
- Read-only descriptors
- A First Example
- Computed Attributes
- Using State Information in Descriptors
- How Properties and Descriptors Relate
- Descriptors and slots and more
- The Basics
- __getattr__ and __getattribute__
- The Basics
- Avoiding loops in attribute interception methods
- A First Example
- Using __getattribute__
- Computed Attributes
- Using __getattribute__
- __getattr__ and __getattribute__ Compared
- Management Techniques Compared
- Intercepting Built-in Operation Attributes
- Revisiting Chapter 28s delegation example
- The Basics
- Example: Attribute Validations
- Using Properties to Validate
- Testing code
- Using Descriptors to Validate
- Option 1: Validating with shared descriptor-instance state (badly!)
- Option 2: Validating with per-client-instance state (correctly)
- Using __getattr__ to Validate
- Using __getattribute__ to Validate
- Using Properties to Validate
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- Why Manage Attributes?
- 39. Decorators
- Whats a Decorator?
- Managing Calls and Instances
- Managing Functions and Classes
- Using and Defining Decorators
- Why Decorators?
- The Basics
- Function Decorator Basics
- Usage
- Implementation
- Supporting method decoration
- Class Decorator Basics
- Usage
- Implementation
- Supporting multiple instances
- Decorator Nesting
- Decorator Arguments
- Decorators Manage Functions and Classes, Too
- Function Decorator Basics
- Coding Function Decorators
- Tracing Function Calls
- Decorator State Retention Options
- State with class-instance attributes
- State with global variables
- State with enclosing-scope nonlocals
- State with function attributes
- Class Pitfall: Decorating Methods
- Using nested functions to decorate methods
- Using descriptors to decorate methods
- Timing Function Calls
- Adding Decorator Arguments
- Coding Class Decorators
- Singleton Classes
- Singleton coding alternatives
- Tracing Object Interfaces
- The nondecorator approach
- The class-decorator approach
- Applying class decorators to built-in types
- Class Pitfall: Retaining Multiple Instances
- Singleton Classes
- Example: Private and Public Attributes
- Implementing Private Attributes
- Implementation Details I
- Inheritance versus delegation
- Decorator arguments
- State retention and enclosing scopes
- Using __dict__ and __slots__ (and other virtuals)
- Generalizing for Public Declarations
- Implementation Details II
- Using __X pseudoprivate names
- Breaking privacy
- Decorator trade-offs
- Delegating Built-In Operations
- Workaround: Coding operator-overloading methods inline
- Workaround: Coding operator-overloading methods in superclasses
- Workaround: Generating operator-overloading descriptors
- Example: Validating Function Arguments
- The Goal
- A Basic Range-Testing Decorator for Positional Arguments
- Generalizing for Keywords and Defaults
- Implementation Details
- Function introspection
- Argument assumptions
- Matching algorithm
- Open Issues
- Invalid calls
- Arbitrary arguments
- Decorator nesting
- Decorator Arguments Versus Function Annotations
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- Whats a Decorator?
- 40. Metaclasses and Inheritance
- To Metaclass or Not to Metaclass
- The Downside of Helper Functions
- Metaclasses Versus Class Decorators: Round 1
- The Metaclass Model
- Classes Are Instances of type
- Metaclasses Are Subclasses of type
- Class Statements Call a type
- Class Statements Can Choose a type
- Metaclass Method Protocol
- Coding Metaclasses
- A Basic Metaclass
- Customizing Construction and Initialization
- Other Metaclass Coding Techniques
- Using simple factory functions
- Overloading class creation calls with normal classes
- Managing Classes with Metaclasses and Decorators
- Adding methods to classes
- Automatically decorating class methods
- Inheritance: The Finale
- Metaclass Versus Superclass
- Metaclass Inheritance
- Python Inheritance Algorithm: The Simple Version
- The descriptors deviation
- Python Inheritance Algorithm: The Less Simple Version
- The assignment addendum
- The super supplement
- The built-ins bifurcation
- The Inheritance Wrap-Up
- Metaclass Methods
- Metaclass Methods Versus Class Methods
- Operator Overloading in Metaclass Methods
- Metaclass Methods Versus Instance Methods
- Chapter Summary
- Test Your Knowledge: Quiz
- Test Your Knowledge: Answers
- To Metaclass or Not to Metaclass
- 41. All Good Things
- The Python Tsunami
- The Python Sandbox
- The Python Upside
- Closing Thoughts
- Where to Go from Here
- Encore: Print Your Own Completion Certificate!
- IX. Appendixes
- A. Platform Usage Tips
- Using Python on Windows
- Using Python on macOS
- Using Python on Linux
- Using Python on Android
- Using Python on iOS
- Standalone Apps and Executables
- Etcetera
- B. Solutions to End-of-Part Exercises
- Part I, Getting Started
- Part II, Objects and Operations
- Part III, Statements and Syntax
- Part IV, Functions and Generators
- Part V, Modules and Packages
- Part VI, Classes and OOP
- Part VII, Exceptions
- Index