ebook img

Python Distilled PDF

355 Pages·2021·2.972 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Python Distilled

Python Distilled This page intentionally left blank Python Distilled David M. Beazley Boston•Columbus•NewYork•SanFrancisco•Amsterdam•CapeTown Dubai•London•Madrid•Milan•Munich•Paris•Montreal•Toronto•Delhi•MexicoCity SãoPaulo•Sydney•HongKong•Seoul•Singapore•Taipei•Tokyo Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproductsareclaimedas trademarks.Wherethosedesignationsappearinthisbook,andthepublisherwasawareofatrademark claim,thedesignationshavebeenprintedwithinitialcapitallettersorinallcapitals. Theauthorandpublisherhavetakencareinthepreparationofthisbook,butmakenoexpressedor impliedwarrantyofanykindandassumenoresponsibilityforerrorsoromissions.Noliabilityisassumed forincidentalorconsequentialdamagesinconnectionwithorarisingoutoftheuseoftheinformationor programscontainedherein. Forinformationaboutbuyingthistitleinbulkquantities,orforspecialsalesopportunities(whichmay includeelectronicversions;customcoverdesigns;andcontentparticulartoyourbusiness,traininggoals, marketingfocus,orbrandinginterests),pleasecontactourcorporatesalesdepartment at [email protected] or (800)382-3419. Forgovernmentsalesinquiries,pleasecontact [email protected]. ForquestionsaboutsalesoutsidetheU.S.,pleasecontact [email protected]. VisitusontheWeb:informit.com/aw LibraryofCongressControlNumber:2021943288 Copyright©2022PearsonEducation,Inc. CoverillustrationbyEHStockphoto/Shutterstock Allrightsreserved.Thispublicationisprotectedbycopyright,andpermissionmustbeobtainedfromthe publisherpriortoanyprohibitedreproduction,storageinaretrievalsystem,ortransmissioninanyformor byanymeans,electronic,mechanical,photocopying,recording,orlikewise.Forinformationregarding permissions,requestformsandtheappropriatecontactswithinthePearsonEducationGlobalRights& PermissionsDepartment,pleasevisitwww.pearson.com/permissions. ISBN-13:978-0-13-417327-6 ISBN-10:0-13-417327-9 ScoutAutomatedPrintCode Contents Preface xiii 1 Python Basics 1 1.1 RunningPython 1 1.2 PythonPrograms 2 1.3 Primitives,Variables,and Expressions 3 1.4 ArithmeticOperators 5 1.5 ConditionalsandControlFlow 7 1.6 TextStrings 9 1.7 FileInputandOutput 12 1.8 Lists 13 1.9 Tuples 15 1.10 Sets 17 1.11 Dictionaries 18 1.12 IterationandLooping 21 1.13 Functions 22 1.14 Exceptions 24 1.15 ProgramTermination 26 1.16 ObjectsandClasses 26 1.17 Modules 30 1.18 ScriptWriting 32 1.19 Packages 33 1.20 StructuringanApplication 34 1.21 ManagingThird-PartyPackages 35 1.22 Python:ItFitsYourBrain 36 2 Operators, Expressions, and Data Manipulation 37 2.1 Literals 37 2.2 ExpressionsandLocations 38 2.3 StandardOperators 39 2.4 In-PlaceAssignment 41 2.5 ObjectComparison 42 2.6 OrderedComparisonOperators 42 vi Contents 2.7 BooleanExpressionsandTruth Values 43 2.8 ConditionalExpressions 44 2.9 OperationsInvolvingIterables 45 2.10 OperationsonSequences 47 2.11 OperationsonMutable Sequences 49 2.12 OperationsonSets 50 2.13 OperationsonMappings 51 2.14 List,Set,andDictionary Comprehensions 52 2.15 GeneratorExpressions 54 2.16 TheAttribute(.)Operator 56 2.17 TheFunctionCall()Operator 56 2.18 OrderofEvaluation 56 2.19 FinalWords:TheSecretLifeof Data 58 3 Program Structure and Control Flow 59 3.1 ProgramStructureand Execution 59 3.2 ConditionalExecution 59 3.3 LoopsandIteration 60 3.4 Exceptions 64 3.4.1 TheException Hierarchy 67 3.4.2 ExceptionsandControl Flow 68 3.4.3 DefiningNew Exceptions 69 3.4.4 ChainedExceptions 70 3.4.5 Exception Tracebacks 73 3.4.6 ExceptionHandling Advice 73 3.5 ContextManagersandthewith Statement 75 3.6 Assertionsand__debug__ 77 3.7 FinalWords 78 Contents vii 4 Objects, Types, and Protocols 79 4.1 EssentialConcepts 79 4.2 ObjectIdentityandType 80 4.3 ReferenceCountingandGarbage Collection 81 4.4 ReferencesandCopies 83 4.5 ObjectRepresentationandPrinting 84 4.6 First-ClassObjects 85 4.7 UsingNoneforOptionalorMissing Data 87 4.8 ObjectProtocolsandData Abstraction 87 4.9 ObjectProtocol 89 4.10 NumberProtocol 90 4.11 ComparisonProtocol 92 4.12 ConversionProtocols 94 4.13 ContainerProtocol 95 4.14 IterationProtocol 97 4.15 AttributeProtocol 98 4.16 FunctionProtocol 98 4.17 ContextManagerProtocol 99 4.18 FinalWords:OnBeingPythonic 99 5 Functions 101 5.1 FunctionDefinitions 101 5.2 DefaultArguments 101 5.3 VariadicArguments 102 5.4 KeywordArguments 103 5.5 VariadicKeywordArguments 104 5.6 FunctionsAcceptingAllInputs 104 5.7 Positional-OnlyArguments 105 5.8 Names,DocumentationStrings,andType Hints 106 5.9 FunctionApplicationandParameter Passing 107 5.10 ReturnValues 109 5.11 ErrorHandling 110 5.12 ScopingRules 111 5.13 Recursion 114 viii Contents 5.14 ThelambdaExpression 114 5.15 Higher-OrderFunctions 115 5.16 ArgumentPassinginCallback Functions 118 5.17 ReturningResultsfrom Callbacks 121 5.18 Decorators 124 5.19 Map,Filter,andReduce 127 5.20 FunctionIntrospection,Attributes, andSignatures 129 5.21 EnvironmentInspection 131 5.22 DynamicCodeExecutionand Creation 133 5.23 AsynchronousFunctionsand await 135 5.24 FinalWords:ThoughtsonFunctions andComposition 137 6 Generators 139 6.1 Generatorsandyield 139 6.2 RestartableGenerators 142 6.3 GeneratorDelegation 142 6.4 UsingGeneratorsinPractice 144 6.5 EnhancedGeneratorsandyield Expressions 146 6.6 ApplicationsofEnhanced Generators 148 6.7 GeneratorsandtheBridgeto Awaiting 151 6.8 FinalWords:ABriefHistoryof GeneratorsandLooking Forward 152 7 Classes and Object-Oriented Programming 153 7.1 Objects 153 7.2 TheclassStatement 154 7.3 Instances 155 7.4 AttributeAccess 156 7.5 ScopingRules 158 Contents ix 7.6 OperatorOverloadingandProtocols 159 7.7 Inheritance 160 7.8 AvoidingInheritanceviaComposition 163 7.9 AvoidingInheritanceviaFunctions 166 7.10 DynamicBindingandDuckTyping 167 7.11 TheDangerofInheritingfromBuilt-in Types 167 7.12 ClassVariablesandMethods 169 7.13 StaticMethods 173 7.14 AWordaboutDesignPatterns 176 7.15 DataEncapsulationandPrivate Attributes 176 7.16 TypeHinting 179 7.17 Properties 180 7.18 Types,Interfaces,andAbstractBase Classes 183 7.19 MultipleInheritance,Interfaces,and Mixins 187 7.20 Type-BasedDispatch 193 7.21 ClassDecorators 194 7.22 SupervisedInheritance 197 7.23 TheObjectLifeCycleandMemory Management 199 7.24 WeakReferences 204 7.25 InternalObjectRepresentationand AttributeBinding 206 7.26 Proxies,Wrappers,andDelegation 208 7.27 ReducingMemoryUsewith __slots__ 210 7.28 Descriptors 211 7.29 ClassDefinitionProcess 215 7.30 DynamicClassCreation 216 7.31 Metaclasses 217 7.32 Built-inObjectsforInstancesand Classes 222 7.33 FinalWords:KeepItSimple 223 8 Modules and Packages 225 8.1 ModulesandtheimportStatement 225

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.