第1页 | Learning Python | 阅读 ‧ 电子书库

同步阅读进度,多语言翻译,过滤屏幕蓝光,评论分享,更多完整功能,更好读书体验,试试 阅读 ‧ 电子书库

Learning Python

Table of Contents

SPECIAL OFFER: Upgrade this ebook with O’ReillyPrefaceAbout This Fourth EditionCoverage for Both 3.0 and 2.6New ChaptersChanges to Existing MaterialSpecific Language Extensions in 2.6 and 3.0Specific Language Removals in 3.0About The Third EditionThe Third Edition’s Python Language ChangesThe Third Edition’s Python Training ChangesThe Third Edition’s Structural ChangesThe Third Edition’s Scope ChangesAbout This BookThis Book’s PrerequisitesThis Book’s Scope and Other BooksThis Book’s Style and StructureBook UpdatesAbout the Programs in This BookUsing Code ExamplesFont ConventionsSafari® Books OnlineHow to Contact UsAcknowledgmentsI. Getting Started1. A Python Q&A SessionWhy Do People Use Python?Software QualityDeveloper ProductivityIs Python a “Scripting Language”?OK, but What’s the Downside?Who Uses Python Today?What Can I Do with Python?Systems ProgrammingGUIsInternet ScriptingComponent IntegrationDatabase ProgrammingRapid PrototypingNumeric and Scientific ProgrammingGaming, Images, Serial Ports, XML, Robots, and MoreHow Is Python Supported?What Are Python’s Technical Strengths?It’s Object-OrientedIt’s FreeIt’s PortableIt’s PowerfulIt’s MixableIt’s Easy to UseIt’s Easy to LearnIt’s Named After Monty PythonHow Does Python Stack Up to Language X?Chapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers2. How Python Runs ProgramsIntroducing the Python InterpreterProgram ExecutionThe Programmer’s ViewPython’s ViewExecution Model VariationsPython Implementation AlternativesExecution Optimization ToolsFrozen BinariesOther Execution OptionsFuture Possibilities?Chapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers3. How You Run ProgramsThe Interactive PromptRunning Code InteractivelyWhy the Interactive Prompt?Using the Interactive PromptSystem Command Lines and FilesA First ScriptRunning Files with Command LinesUsing Command Lines and FilesUnix Executable Scripts (#!)Clicking File IconsClicking Icons on WindowsThe input TrickOther Icon-Click LimitationsModule Imports and ReloadsThe Grander Module Story: Attributesimport and reload Usage NotesUsing exec to Run Module FilesThe IDLE User InterfaceIDLE BasicsUsing IDLEAdvanced IDLE ToolsOther IDEsOther Launch OptionsEmbedding CallsFrozen Binary ExecutablesText Editor Launch OptionsStill Other Launch OptionsFuture Possibilities?Which Option Should I Use?Chapter SummaryTest Your Knowledge: QuizTest Your Knowledge: AnswersTest Your Knowledge: Part I ExercisesII. Types and Operations4. Introducing Python Object TypesWhy Use Built-in Types?Python’s Core Data TypesNumbersStringsSequence OperationsImmutabilityType-Specific MethodsGetting HelpOther Ways to Code StringsPattern MatchingListsSequence OperationsType-Specific OperationsBounds CheckingNestingComprehensionsDictionariesMapping OperationsNesting RevisitedSorting Keys: for LoopsIteration and OptimizationMissing Keys: if TestsTuplesWhy Tuples?FilesOther File-Like ToolsOther Core TypesHow to Break Your Code’s FlexibilityUser-Defined ClassesAnd Everything ElseChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers5. Numeric TypesNumeric Type BasicsNumeric LiteralsBuilt-in Numeric ToolsPython Expression OperatorsNumbers in ActionVariables and Basic ExpressionsNumeric Display FormatsComparisons: Normal and ChainedDivision: Classic, Floor, and TrueInteger PrecisionComplex NumbersHexadecimal, Octal, and Binary NotationBitwise OperationsOther Built-in Numeric ToolsOther Numeric TypesDecimal TypeFraction TypeSetsBooleansNumeric ExtensionsChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers6. The Dynamic Typing InterludeThe Case of the Missing Declaration StatementsVariables, Objects, and ReferencesTypes Live with Objects, Not VariablesObjects Are Garbage-CollectedShared ReferencesShared References and In-Place ChangesShared References and EqualityDynamic Typing Is EverywhereChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers7. StringsString LiteralsSingle- and Double-Quoted Strings Are the SameEscape Sequences Represent Special BytesRaw Strings Suppress EscapesTriple Quotes Code Multiline Block StringsStrings in ActionBasic OperationsIndexing and SlicingString Conversion ToolsChanging StringsString MethodsString Method Examples: Changing StringsString Method Examples: Parsing TextOther Common String Methods in ActionThe Original string Module (Gone in 3.0)String Formatting ExpressionsAdvanced String Formatting ExpressionsDictionary-Based String Formatting ExpressionsString Formatting Method CallsThe BasicsAdding Keys, Attributes, and OffsetsAdding Specific FormattingComparison to the % Formatting ExpressionWhy the New Format Method?General Type CategoriesTypes Share Operation Sets by CategoriesMutable Types Can Be Changed In-PlaceChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers8. Lists and DictionariesListsLists in ActionBasic List OperationsList Iteration and ComprehensionsIndexing, Slicing, and MatrixesChanging Lists In-PlaceDictionariesDictionaries in ActionBasic Dictionary OperationsChanging Dictionaries In-PlaceMore Dictionary MethodsA Languages TableDictionary Usage NotesOther Ways to Make DictionariesDictionary Changes in Python 3.0Chapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers9. Tuples, Files, and Everything ElseTuplesTuples in ActionWhy Lists and Tuples?FilesOpening FilesUsing FilesFiles in ActionOther File ToolsType Categories RevisitedObject FlexibilityReferences Versus CopiesComparisons, Equality, and TruthPython 3.0 Dictionary ComparisonsThe Meaning of True and False in PythonPython’s Type HierarchiesType ObjectsOther Types in PythonBuilt-in Type GotchasAssignment Creates References, Not CopiesRepetition Adds One Level DeepBeware of Cyclic Data StructuresImmutable Types Can’t Be Changed In-PlaceChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: AnswersTest Your Knowledge: Part II ExercisesIII. Statements and Syntax10. Introducing Python StatementsPython Program Structure RevisitedPython’s StatementsA Tale of Two ifsWhat Python AddsWhat Python RemovesWhy Indentation Syntax?A Few Special CasesA Quick Example: Interactive LoopsA Simple Interactive LoopDoing Math on User InputsHandling Errors by Testing InputsHandling Errors with try StatementsNesting Code Three Levels DeepChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers11. Assignments, Expressions, and PrintsAssignment StatementsAssignment Statement FormsSequence AssignmentsExtended Sequence Unpacking in Python 3.0Multiple-Target AssignmentsAugmented AssignmentsVariable Name RulesExpression StatementsExpression Statements and In-Place ChangesPrint OperationsThe Python 3.0 print FunctionThe Python 2.6 print StatementPrint Stream RedirectionVersion-Neutral PrintingChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers12. if Tests and Syntax Rulesif StatementsGeneral FormatBasic ExamplesMultiway BranchingPython Syntax RulesBlock Delimiters: Indentation RulesStatement Delimiters: Lines and ContinuationsA Few Special CasesTruth TestsThe if/else Ternary ExpressionChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers13. while and for Loopswhile LoopsGeneral FormatExamplesbreak, continue, pass, and the Loop elseGeneral Loop FormatpasscontinuebreakLoop elsefor LoopsGeneral FormatExamplesLoop Coding TechniquesCounter Loops: while and rangeNonexhaustive Traversals: range and SlicesChanging Lists: rangeParallel Traversals: zip and mapGenerating Both Offsets and Items: enumerateChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers14. Iterations and Comprehensions, Part 1Iterators: A First LookThe Iteration Protocol: File IteratorsManual Iteration: iter and nextOther Built-in Type IteratorsList Comprehensions: A First LookList Comprehension BasicsUsing List Comprehensions on FilesExtended List Comprehension SyntaxOther Iteration ContextsNew Iterables in Python 3.0The range IteratorThe map, zip, and filter IteratorsMultiple Versus Single IteratorsDictionary View IteratorsOther Iterator TopicsChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers15. The Documentation InterludePython Documentation Sources# CommentsThe dir FunctionDocstrings: __doc__PyDoc: The help FunctionPyDoc: HTML ReportsThe Standard Manual SetWeb ResourcesPublished BooksCommon Coding GotchasChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: AnswersTest Your Knowledge: Part III ExercisesIV. Functions16. Function BasicsWhy Use Functions?Coding Functionsdef Statementsdef Executes at RuntimeA First Example: Definitions and CallsDefinitionCallsPolymorphism in PythonA Second Example: Intersecting SequencesDefinitionCallsPolymorphism RevisitedLocal VariablesChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers17. ScopesPython Scope BasicsScope RulesName Resolution: The LEGB RuleScope ExampleThe Built-in ScopeThe global StatementMinimize Global VariablesMinimize Cross-File ChangesOther Ways to Access GlobalsScopes and Nested FunctionsNested Scope DetailsNested Scope ExamplesThe nonlocal Statementnonlocal Basicsnonlocal in ActionWhy nonlocal?Chapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers18. ArgumentsArgument-Passing BasicsArguments and Shared ReferencesAvoiding Mutable Argument ChangesSimulating Output ParametersSpecial Argument-Matching ModesThe BasicsMatching SyntaxThe Gritty DetailsKeyword and Default ExamplesArbitrary Arguments ExamplesPython 3.0 Keyword-Only ArgumentsThe min Wakeup Call!Full CreditBonus PointsThe Punch Line...Generalized Set FunctionsEmulating the Python 3.0 print FunctionUsing Keyword-Only ArgumentsChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers19. Advanced Function TopicsFunction Design ConceptsRecursive FunctionsSummation with RecursionCoding AlternativesLoop Statements Versus RecursionHandling Arbitrary StructuresFunction Objects: Attributes and AnnotationsIndirect Function CallsFunction IntrospectionFunction AttributesFunction Annotations in 3.0Anonymous Functions: lambdalambda BasicsWhy Use lambda?How (Not) to Obfuscate Your Python CodeNested lambdas and ScopesMapping Functions over Sequences: mapFunctional Programming Tools: filter and reduceChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers20. Iterations and Comprehensions, Part 2List Comprehensions Revisited: Functional ToolsList Comprehensions Versus mapAdding Tests and Nested Loops: filterList Comprehensions and MatrixesComprehending List ComprehensionsIterators Revisited: GeneratorsGenerator Functions: yield Versus returnGenerator Expressions: Iterators Meet ComprehensionsGenerator Functions Versus Generator ExpressionsGenerators Are Single-Iterator ObjectsEmulating zip and map with Iteration ToolsValue Generation in Built-in Types and Classes3.0 Comprehension Syntax SummaryComprehending Set and Dictionary ComprehensionsExtended Comprehension Syntax for Sets and DictionariesTiming Iteration AlternativesTiming ModuleTiming ScriptTiming ResultsTiming Module AlternativesOther SuggestionsFunction GotchasLocal Names Are Detected StaticallyDefaults and Mutable ObjectsFunctions Without returnsEnclosing Scope Loop VariablesChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: AnswersTest Your Knowledge: Part IV ExercisesV. Modules21. Modules: The Big PictureWhy Use Modules?Python Program ArchitectureHow to Structure a ProgramImports and AttributesStandard Library ModulesHow Imports Work1. Find It2. Compile It (Maybe)3. Run ItThe Module Search PathConfiguring the Search PathSearch Path VariationsThe sys.path ListModule File SelectionAdvanced Module Selection ConceptsChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers22. Module Coding BasicsModule CreationModule UsageThe import StatementThe from StatementThe from * StatementImports Happen Only Onceimport and from Are AssignmentsCross-File Name Changesimport and from EquivalencePotential Pitfalls of the from StatementModule NamespacesFiles Generate NamespacesAttribute Name QualificationImports Versus ScopesNamespace NestingReloading Modulesreload Basicsreload ExampleChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers23. Module PackagesPackage Import BasicsPackages and Search Path SettingsPackage __init__.py FilesPackage Import Examplefrom Versus import with PackagesWhy Use Package Imports?A Tale of Three SystemsPackage Relative ImportsChanges in Python 3.0Relative Import BasicsWhy Relative Imports?The Scope of Relative ImportsModule Lookup Rules SummaryRelative Imports in ActionChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers24. Advanced Module TopicsData Hiding in ModulesMinimizing from * Damage: _X and __all__Enabling Future Language FeaturesMixed Usage Modes: __name__ and __main__Unit Tests with __name__Using Command-Line Arguments with __name__Changing the Module Search PathThe as Extension for import and fromModules Are Objects: MetaprogramsImporting Modules by Name StringTransitive Module ReloadsModule Design ConceptsModule GotchasStatement Order Matters in Top-Level Codefrom Copies Names but Doesn’t Linkfrom * Can Obscure the Meaning of Variablesreload May Not Impact from Importsreload, from, and Interactive TestingRecursive from Imports May Not WorkChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: AnswersTest Your Knowledge: Part V ExercisesVI. Classes and OOP25. OOP: The Big PictureWhy Use Classes?OOP from 30,000 FeetAttribute Inheritance SearchClasses and InstancesClass Method CallsCoding Class TreesOOP Is About Code ReuseChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers26. Class Coding BasicsClasses Generate Multiple Instance ObjectsClass Objects Provide Default BehaviorInstance Objects Are Concrete ItemsA First ExampleClasses Are Customized by InheritanceA Second ExampleClasses Are Attributes in ModulesClasses Can Intercept Python OperatorsA Third ExampleWhy Use Operator Overloading?The World’s Simplest Python ClassClasses Versus DictionariesChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers27. A More Realistic ExampleStep 1: Making InstancesCoding ConstructorsTesting As You GoUsing Code Two WaysStep 2: Adding Behavior MethodsCoding MethodsStep 3: Operator OverloadingProviding Print DisplaysStep 4: Customizing Behavior by SubclassingCoding SubclassesAugmenting Methods: The Bad WayAugmenting Methods: The Good WayPolymorphism in ActionInherit, Customize, and ExtendOOP: The Big IdeaStep 5: Customizing Constructors, TooOOP Is Simpler Than You May ThinkOther Ways to Combine ClassesStep 6: Using Introspection ToolsSpecial Class AttributesA Generic Display ToolInstance Versus Class AttributesName Considerations in Tool ClassesOur Classes’ Final FormStep 7 (Final): Storing Objects in a DatabasePickles and ShelvesStoring Objects on a Shelve DatabaseExploring Shelves InteractivelyUpdating Objects on a ShelveFuture DirectionsChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers28. Class Coding DetailsThe class StatementGeneral FormExampleMethodsMethod ExampleCalling Superclass ConstructorsOther Method Call PossibilitiesInheritanceAttribute Tree ConstructionSpecializing Inherited MethodsClass Interface TechniquesAbstract SuperclassesPython 2.6 and 3.0 Abstract SuperclassesNamespaces: The Whole StorySimple Names: Global Unless AssignedAttribute Names: Object NamespacesThe “Zen” of Python Namespaces: Assignments Classify NamesNamespace DictionariesNamespace LinksDocumentation Strings RevisitedClasses Versus ModulesChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers29. Operator OverloadingThe BasicsConstructors and Expressions: __init__ and __sub__Common Operator Overloading MethodsIndexing and Slicing: __getitem__ and __setitem__Intercepting SlicesIndex Iteration: __getitem__Iterator Objects: __iter__ and __next__User-Defined IteratorsMultiple Iterators on One ObjectMembership: __contains__, __iter__, and __getitem__Attribute Reference: __getattr__ and __setattr__Other Attribute Management ToolsEmulating Privacy for Instance Attributes: Part 1String Representation: __repr__ and __str__Right-Side and In-Place Addition: __radd__ and __iadd__In-Place AdditionCall Expressions: __call__Function Interfaces and Callback-Based CodeComparisons: __lt__, __gt__, and OthersThe 2.6 __cmp__ Method (Removed in 3.0)Boolean Tests: __bool__ and __len__Object Destruction: __del__Chapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers30. Designing with ClassesPython and OOPOverloading by Call Signatures (or Not)OOP and Inheritance: “Is-a” RelationshipsOOP and Composition: “Has-a” RelationshipsStream Processors RevisitedOOP and Delegation: “Wrapper” ObjectsPseudoprivate Class AttributesName Mangling OverviewWhy Use Pseudoprivate Attributes?Methods Are Objects: Bound or UnboundUnbound Methods are Functions in 3.0Bound Methods and Other Callable ObjectsMultiple Inheritance: “Mix-in” ClassesCoding Mix-in Display ClassesClasses Are Objects: Generic Object FactoriesWhy Factories?Other Design-Related TopicsChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers31. Advanced Class TopicsExtending Built-in TypesExtending Types by EmbeddingExtending Types by SubclassingThe “New-Style” Class ModelNew-Style Class ChangesType Model ChangesDiamond Inheritance ChangeNew-Style Class ExtensionsInstance SlotsClass Properties__getattribute__ and DescriptorsMetaclassesStatic and Class MethodsWhy the Special Methods?Static Methods in 2.6 and 3.0Static Method AlternativesUsing Static and Class MethodsCounting Instances with Static MethodsCounting Instances with Class MethodsDecorators and Metaclasses: Part 1Function Decorator BasicsA First Function Decorator ExampleClass Decorators and MetaclassesFor More DetailsClass GotchasChanging Class Attributes Can Have Side EffectsChanging Mutable Class Attributes Can Have Side Effects, TooMultiple Inheritance: Order MattersMethods, Classes, and Nested ScopesDelegation-Based Classes in 3.0: __getattr__ and built-ins“Overwrapping-itis”Chapter SummaryTest Your Knowledge: QuizTest Your Knowledge: AnswersTest Your Knowledge: Part VI ExercisesVII. Exceptions and Tools32. Exception BasicsWhy Use Exceptions?Exception RolesExceptions: The Short StoryDefault Exception HandlerCatching ExceptionsRaising ExceptionsUser-Defined ExceptionsTermination ActionsChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers33. Exception Coding DetailsThe try/except/else Statementtry Statement ClausesThe try else ClauseExample: Default BehaviorExample: Catching Built-in ExceptionsThe try/finally StatementExample: Coding Termination Actions with try/finallyUnified try/except/finallyUnified try Statement SyntaxCombining finally and except by NestingUnified try ExampleThe raise StatementPropagating Exceptions with raisePython 3.0 Exception Chaining: raise fromThe assert StatementExample: Trapping Constraints (but Not Errors!)with/as Context ManagersBasic UsageThe Context Management ProtocolChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers34. Exception ObjectsExceptions: Back to the FutureString Exceptions Are Right Out!Class-Based ExceptionsCoding Exceptions ClassesWhy Exception Hierarchies?Built-in Exception ClassesBuilt-in Exception CategoriesDefault Printing and StateCustom Print DisplaysCustom Data and BehaviorProviding Exception DetailsProviding Exception MethodsChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers35. Designing with ExceptionsNesting Exception HandlersExample: Control-Flow NestingExample: Syntactic NestingException IdiomsExceptions Aren’t Always ErrorsFunctions Can Signal Conditions with raiseClosing Files and Server ConnectionsDebugging with Outer try StatementsRunning In-Process TestsMore on sys.exc_infoException Design Tips and GotchasWhat Should Be WrappedCatching Too Much: Avoid Empty except and ExceptionCatching Too Little: Use Class-Based CategoriesCore Language SummaryThe Python ToolsetDevelopment Tools for Larger ProjectsChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: AnswersTest Your Knowledge: Part VII ExercisesVIII. Advanced Topics36. Unicode and Byte StringsString Changes in 3.0String BasicsCharacter Encoding SchemesPython’s String TypesText and Binary FilesPython 3.0 Strings in ActionLiterals and Basic PropertiesConversionsCoding Unicode StringsCoding ASCII TextCoding Non-ASCII TextEncoding and Decoding Non-ASCII textOther Unicode Coding TechniquesConverting EncodingsCoding Unicode Strings in Python 2.6Source File Character Set Encoding DeclarationsUsing 3.0 Bytes ObjectsMethod CallsSequence OperationsOther Ways to Make bytes ObjectsMixing String TypesUsing 3.0 (and 2.6) bytearray ObjectsUsing Text and Binary FilesText File BasicsText and Binary Modes in 3.0Type and Content MismatchesUsing Unicode FilesReading and Writing Unicode in 3.0Handling the BOM in 3.0Unicode Files in 2.6Other String Tool Changes in 3.0The re Pattern Matching ModuleThe struct Binary Data ModuleThe pickle Object Serialization ModuleXML Parsing ToolsChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers37. Managed AttributesWhy Manage Attributes?Inserting Code to Run on Attribute AccessPropertiesThe BasicsA First ExampleComputed AttributesCoding Properties with DecoratorsDescriptorsThe BasicsA First ExampleComputed AttributesUsing State Information in DescriptorsHow Properties and Descriptors Relate__getattr__ and __getattribute__The BasicsA First ExampleComputed Attributes__getattr__ and __getattribute__ ComparedManagement Techniques ComparedIntercepting Built-in Operation AttributesDelegation-Based Managers RevisitedExample: Attribute ValidationsUsing Properties to ValidateUsing Descriptors to ValidateUsing __getattr__ to ValidateUsing __getattribute__ to ValidateChapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers38. DecoratorsWhat’s a Decorator?Managing Calls and InstancesManaging Functions and ClassesUsing and Defining DecoratorsWhy Decorators?The BasicsFunction DecoratorsClass DecoratorsDecorator NestingDecorator ArgumentsDecorators Manage Functions and Classes, TooCoding Function DecoratorsTracing CallsState Information Retention OptionsClass Blunders I: Decorating Class MethodsTiming CallsAdding Decorator ArgumentsCoding Class DecoratorsSingleton ClassesTracing Object InterfacesClass Blunders II: Retaining Multiple InstancesDecorators Versus Manager FunctionsWhy Decorators? (Revisited)Managing Functions and Classes DirectlyExample: “Private” and “Public” AttributesImplementing Private AttributesImplementation Details IGeneralizing for Public Declarations, TooImplementation Details IIOpen IssuesPython Isn’t About ControlExample: Validating Function ArgumentsThe GoalA Basic Range-Testing Decorator for Positional ArgumentsGeneralizing for Keywords and Defaults, TooImplementation DetailsOpen IssuesDecorator Arguments Versus Function AnnotationsOther Applications: Type Testing (If You Insist!)Chapter SummaryTest Your Knowledge: QuizTest Your Knowledge: Answers39. MetaclassesTo Metaclass or Not to MetaclassIncreasing Levels of MagicThe Downside of “Helper” FunctionsMetaclasses Versus Class Decorators: Round 1The Metaclass ModelClasses Are Instances of typeMetaclasses Are Subclasses of TypeClass Statement ProtocolDeclaring MetaclassesCoding MetaclassesA Basic MetaclassCustomizing Construction and InitializationOther Metaclass Coding TechniquesInstances Versus InheritanceExample: Adding Methods to ClassesManual AugmentationMetaclass-Based AugmentationMetaclasses Versus Class Decorators: Round 2Example: Applying Decorators to MethodsTracing with Decoration ManuallyTracing with Metaclasses and DecoratorsApplying Any Decorator to MethodsMetaclasses Versus Class Decorators: Round 3Chapter SummaryTest Your Knowledge: QuizTest Your Knowledge: AnswersIX. AppendixesA. Installation and ConfigurationInstalling the Python InterpreterIs Python Already Present?Where to Get PythonInstallation StepsConfiguring PythonPython Environment VariablesHow to Set Configuration OptionsPython Command-Line OptionsFor More HelpB. Solutions to End-of-Part ExercisesPart I, Getting StartedPart II, Types and OperationsPart III, Statements and SyntaxPart IV, FunctionsPart V, ModulesPart VI, Classes and OOPPart VII, Exceptions and ToolsIndexSPECIAL OFFER: Upgrade this ebook with O’Reilly

请支持我们,让我们可以支付服务器费用。
使用微信支付打赏


 下一页


下载 · 书页 · 阅读 ‧ 电子书库