id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
1,300 | that' the story todaychange is always possibility in open source projects (indeedthe prior edition quoted plans on string formatting and relative imports in that were later abandoned)so as usualbe sure to watch for future developments on this front given the performance advantage and auto-initialization code of regular packagesthoughit seems unlikely that they would be removed altogether namespace packages in action to see how namespace packages workconsider the following two modules and nested directory structure--with two subdirectories named sub located in different parent directoriesdir and dir :\code\ns\dir \sub\mod py :\code\ns\dir \sub\mod py if we add both dir and dir to the module search pathsub becomes namespace package spanning bothwith the two module files available under that name even though they live in separate physical directories here' the filescontents and the required path settings on windowsthere are no __init__ py files here--in fact there cannot be in namespace packagesas this is their chief physical differentiationc:\codemkdir ns\dir \sub :\codemkdir ns\dir \sub two dirs of same name in different dirs and similar outside windows :\codetype ns\dir \sub\mod py print( 'dir \sub\mod 'module files in different directories :\codetype ns\dir \sub\mod py print( 'dir \sub\mod ' :\codeset pythonpath= :\code\ns\dir ; :\code\ns\dir nowwhen imported directly in and laterthe namespace package is the virtual concatenation of its individual directory componentsand allows further nested parts to be accessed through its singlecomposite name with normal importsc:\codec:\python \python import sub sub namespace packagesnested search paths sub __path__ _namespacepath([' :\\code\\ns\\dir \\sub'' :\\code\\ns\\dir \\sub']from sub import mod dir \sub\mod import sub mod dir \sub\mod content from two different directories mod python namespace packages |
1,301 | this is also true if we import through the namespace package name immediately-because the namespace package is made when first reachedthe timing of path extensions is irrelevantc:\codec:\python \python import sub mod dir \sub\mod import sub mod dir \sub\mod one package spanning two directories sub mod sub mod sub sub __path__ _namespacepath([' :\\code\\ns\\dir \\sub'' :\\code\\ns\\dir \\sub']interestinglyrelative imports work in namespace packages too--in the followingthe relative import statement references file in the packageeven though the referenced file resides in different directoryc:\codetype ns\dir \sub\mod py from import mod print( 'dir \sub\mod 'and "from import stringstill fails :\codec:\python \python import sub mod relative import of mod in another dir dir \sub\mod dir \sub\mod import sub mod already imported module not rerun sub mod as you can seenamespace packages are like ordinary single-directory packages in every wayexcept for having split physical storage--which is why single directory namespaces packages without __init__ py files are exactly like regular packagesbut with no initialization logic to be run namespace package nesting namespace packages even support arbitrary nesting--once package namespace package is createdit serves essentially the same role at its level that sys path does at the topbecoming the "parent pathfor lower levels continuing the prior section' examplec:\codemkdir ns\dir \sub\lower further nested components :\codetype ns\dir \sub\lower\mod py module packages |
1,302 | :\codec:\python \python import sub lower mod dir \sub\lower\mod :\codec:\python \python import sub import sub mod dir \sub\mod import sub lower mod dir \sub\lower\mod namespace pkg nested in namespace pkg same effect if accessed incrementally sub lower single-directory namespace pkg sub lower __path__ _namespacepath([' :\\code\\ns\\dir \\sub\\lower']in the precedingsub is namespace package split across two directoriesand sub lower is single-directory namespace package nested within the portion of sub physically located in dir sub lower is also the namespace package equivalent of regular package with no __init__ py this nesting behavior holds true whether the lower component is moduleregular packageor another namespace package--by serving as new import search pathsnamespace packages allow all three to be nested within them freelyc:\codemkdir ns\dir \sub\pkg :\codetype ns\dir \sub\pkg\__init__ py print( 'dir \sub\pkg\__init__ py' :\codec:\python \python import sub mod dir \sub\mod import sub pkg dir \sub\pkg\__init__ py import sub lower mod dir \sub\lower\mod nested module nested regular package nested namespace package sub modulespackages,and namespaces sub mod sub pkg sub lower sub lower mod trace through this example' files and directories for more insight as you can seenamespace packages integrate seamlessly into the former import modelsand extend it with new functionality python namespace packages |
1,303 | as explained earlierpart of the purpose of __init___ py files in regular packages is to declare the directory as package--it tells python to use the directoryrather than skipping ahead to possible file of the same name later on the path this avoids inadvertently choosing noncode subdirectory that accidentally appears early on the pathover desired module of the same name because namespace packages do not require these special filesthey would seem to invalidate this safeguard this isn' the casethough--because the namespace algorithm outlined earlier continues scanning the path after namespace directory has been foundfiles later on the path still have priority over earlier directories with no __init__ py for exampleconsider the following directories and modulesc:\codemkdir ns :\codemkdir ns :\codemkdir ns \dir :\codenotepad ns \dir\ns py :\codetype ns \dir\ns py print( 'ns \dir\ns py!'the ns directory here cannot be imported in python and earlier--it' not regular packageas it lacks an __init__ py initialization file this directory can be imported under though--it' namespace package directory in the current working directorywhich is always the first item on the sys path module search path irrespective of pythonpath settingsc:\codeset pythonpathc:\codepy - import ns importerrorno module named ns :\codepy - import ns ns ns __path__ _namespacepath([\\ns '] single-directory namespace package in cwd but watch what happens when the directory containing file of the same name as namespace directory is added later on the search pathvia pythonpath settings--the file is used insteadbecause python keeps searching later path entries after namespace package directory is found it stops searching only when module or regular package is locatedor the path has been completely scanned namespace packages are returned only if nothing else was found along the wayc:\codeset pythonpath= :\code\ns \dir :\codepy - import ns use later module filenot same-named directoryns \dir\ns pyns module packages |
1,304 | sys path[: [''' :\\code\\ns \\dir'first 'means current working directorycwd in factsetting the path to include module works the same as it does in earlier pythonseven if same-named namespace directory appears earlier on the pathnamespace packages are used in only in cases that would be errors in earlier pythonsc:\codepy - import ns ns \dir\ns pyns this is also why none of the directories in namespace package is allowed to have __init__ py fileas soon as the import algorithm finds one that doesit returns regular package immediatelyand abandons the path search and the namespace package put more formallythe import algorithm chooses namespace package only at the end of the path scanand stops at steps or if either regular package or module file is found sooner the net effect is that both module files and regular packages anywhere on the module search path have precedence over namespace package directories in the followingfor examplea namespace package called sub exists as the concatenation of same-named directories under dir and dir on the pathc:\codemkdir ns \dir \sub :\codemkdir ns \dir \sub :\codeset pythonpath= :\code\ns \dir ; :\code\ns \dir :\codepy - import sub sub sub __path__ _namespacepath([' :\\code\\ns \\dir \\sub'' :\\code\\ns \\dir \\sub']much like module filethougha regular package added in the rightmost path entry takes priority over same-named namespace package directories too--the import path scan starts recording namespace package tentatively in dir as beforebut abandons it when the regular package is detected in dir :\codenotepad ns \dir \sub\__init__ py :\codepy - import sub use later reg packagenot same-named directorysub though useful extensionbecause namespace packages are available only to readers using python (and lateri' going to defer to python' manuals for more details on the subject see especially this change' pep document for this change' rationaleadditional detailsand more comprehensive examples python namespace packages |
1,305 | this introduced python' package import model--an optional but useful way to explicitly list part of the directory path leading up to your modules package imports are still relative to directory on your module import search pathbut your script gives the rest of the path to the module explicitly as we've seenpackages not only make imports more meaningful in larger systemsbut also simplify import search path settings if all cross-directory imports are relative to common root directoryand resolve ambiguities when there is more than one module of the same name--including the name of the enclosing directory in package import helps distinguish between them because it' relevant only to code in packageswe also explored the newer relative import model here-- way for imports in package files to select modules in the same package explicitly using leading dots in frominstead of relying on an older and errorprone implicit package search rule finallywe surveyed python namespace packageswhich allow logical package to span multiple physical directories as fallback option of import searchesand remove the initialization file requirements of the prior model in the next we will survey handful of more advanced module-related topicssuch as the __name__ usage mode variable and name-string imports as usualthoughlet' close out this first with short quiz to review what you've learned here test your knowledgequiz what is the purpose of an __init__ py file in module package directory how can you avoid repeating the full package path every time you reference package' content which directories require __init__ py files when must you use import instead of from with packages what is the difference between from mypkg import spam and from import spam what is namespace packagetest your knowledgeanswers the __init__ py file serves to declare and initialize regular module packagepython automatically runs its code the first time you import through directory in process its assigned variables become the attributes of the module object created in memory to correspond to that directory it is also not optional until and later--you can' import through directory with package syntax unless it contains this file module packages |
1,306 | or use the as extension with the import statement to rename the path to shorter synonym in both casesthe path is listed in only one placein the from or import statement in python and earliereach directory listed in an executed import or from statement must contain an __init__ py file other directoriesincluding the directory that contains the leftmost component of package pathdo not need to include this file you must use import instead of from with packages only if you need to access the same name defined in more than one path with importthe path makes the references uniquebut from allows only one version of any given name (unless you also use the as extension to rename in python xfrom mypkg import spam is an absolute import--the search for mypkg skips the package directory and the module is located in an absolute directory in sys path statement from import spamon the other handis relative import --spam is looked up relative to the package in which this statement is contained only in python xthe absolute import searches the package directory first before proceeding to sys pathrelative imports work as described namespace package is an extension to the import modelavailable in python and laterthat corresponds to one or more directories that do not have __init__ py files when python finds these during an import searchand does not find simple module or regular package firstit creates namespace package that is the virtual concatenation of all found directories having the requested module name further nested components are looked up in all the namespace package' directories the effect is similar to regular packagebut content may be split across multiple directories test your knowledgeanswers |
1,307 | advanced module topics this concludes this part of the book with collection of more advanced module-related topics--data hidingthe __future__ modulethe __name__ variablesys path changeslisting toolsimporting modules by name stringtransitive reloadsand so on--along with the standard set of gotchas and exercises related to what we've covered in this part of the book along the waywe'll build some larger and more useful tools than we have so far that combine functions and modules like functionsmodules are more effective when their interfaces are well definedso this also briefly reviews module design conceptssome of which we have explored in prior despite the word "advancedused in this title for symmetrythis is mostly grab-bag assortment of additional module topics because some of the topics discussed here are widely used--especially the __name__ trick--be sure to browse here before moving on to classes in the next part of the book module design concepts like functionsmodules present design tradeoffsyou have to think about which functions go in which modulesmodule communication mechanismsand so on all of this will become clearer when you start writing bigger python systemsbut here are few general ideas to keep in mindyou're always in module in python there' no way to write code that doesn' live in some module as mentioned briefly in and even code typed at the interactive prompt really goes in built-in module called __main__the only unique things about the interactive prompt are that code runs and is discarded immediatelyand expression results are printed automatically minimize module couplingglobal variables like functionsmodules work best if they're written to be closed boxes as rule of thumbthey should be as independent of global variables used within other modules as possibleexcept for |
1,308 | with the outside world are the tools it usesand the tools it defines maximize module cohesionunified purpose you can minimize module' couplings by maximizing its cohesionif all the components of module share general purposeyou're less likely to depend on external names modules should rarely change other modulesvariables we illustrated this with code in but it' worth repeating hereit' perfectly ok to use globals defined in another module (that' how clients import servicesafter all)but changing globals in another module is often symptom of design problem there are exceptionsof coursebut you should try to communicate results through devices such as function arguments and return valuesnot cross-module changes otherwiseyour globalsvalues become dependent on the order of arbitrarily remote assignments in other filesand your modules become harder to understand and reuse as summaryfigure - sketches the environment in which modules operate modules contain variablesfunctionsclassesand other modules (if importedfunctions have local variables of their ownas do classes--objects that live within modules and which we'll begin studying in the next as we saw in part ivfunctions can nesttoobut all are ultimately contained by modules at the top figure - module execution environment modules are importedbut modules also import and use other moduleswhich may be coded in python or another language such as modules in turn contain variablesfunctionsand classes to do their workand their functions and classes may contain variables and other items of their own at the topthoughprograms are just sets of modules advanced module topics |
1,309 | as we've seena python module exports all the names assigned at the top level of its file there is no notion of declaring which names should and shouldn' be visible outside the module in factthere' no way to prevent client from changing names inside module if it wants to in pythondata hiding in modules is conventionnot syntactical constraint if you want to break module by trashing its namesyou canbut fortunatelyi've yet to meet programmer for whom this was life goal some purists object to this liberal attitude toward data hidingclaiming that it means python can' implement encapsulation howeverencapsulation in python is more about packaging than about restricting we'll expand this idea in the next part in relation to classeswhich also have no privacy syntax but can often emulate its effect in code minimizing from damage_x and __all__ as special caseyou can prefix names with single underscore ( _xto prevent them from being copied out when client imports module' names with from statement this really is intended only to minimize namespace pollutionbecause from copies out all namesthe importer may get more than it' bargained for (including names that overwrite names in the importerunderscores aren' "privatedeclarationsyou can still see and change such names with other import formssuch as the import statementunders py a_bc_d from unders import ac ( _b nameerrorname '_bis not defined load non _x names only import unders unders _b but other importers get every name alternativelyyou can achieve hiding effect similar to the _x naming convention by assigning list of variable name strings to the variable __all__ at the top level of the module when this feature is usedthe from statement will copy out only those names listed in the __all__ list in effectthis is the converse of the _x convention__all__ identifies names to be copiedwhile _x identifies names not to be copied python looks for an __all__ list in the module first and copies its names irrespective of any underscoresif __all__ is not definedfrom copies all names without single leading underscorealls py __all__ [' ''_c'__all__ has precedence over _x data hiding in modules |
1,310 | from alls import a_c ( nameerrorname 'bis not defined load __all__ names only from alls import ab_c_d ab_c_d ( but other importers get every name import alls alls aalls balls _calls _d ( like the _x conventionthe __all__ list has meaning only to the from statement form and does not amount to privacy declarationother import statements can still access all namesas the last two tests show stillmodule writers can use either technique to implement modules that are well behaved when used with from see also the discussion of __all__ lists in package __init__ py files in therethese lists declare submodules to be automatically loaded for from on their container enabling future language features__future__ changes to the language that may potentially break existing code are usually introduced gradually in python they often initially appear as optional extensionswhich are disabled by default to turn on such extensionsuse special import statement of this formfrom __future__ import featurename when used in scriptthis statement must appear as the first executable statement in the file (possibly following docstring or comment)because it enables special compilation of code on per-module basis it' also possible to submit this statement at the interactive prompt to experiment with upcoming language changesthe feature will then be available for the remainder of the interactive session for examplein this book we've seen how to use this statement in python to activate true division in print calls in and absolute imports for packages in prior editions of this book used this statement form to demonstrate generator functionswhich required keyword that was not yet enabled by default (they use featurename of generatorsall of these changes have the potential to break existing code in python xso they were phased in gradually or offered as optional extensionsenabled with this special import at the same timesome are available to allow you to write code that is forward compatible with later releases you may port to someday for list of futurisms you may import and turn on this wayrun dir call on the __future__ module after importing itor see its library manual entry per its documen advanced module topics |
1,311 | __future__ import even in code run by version of python where the feature is present normally mixed usage modes__name__ and __main__ our next module-related trick lets you both import file as module and run it as standalone programand is widely used in python files it' actually so simple that some miss the point at firsteach module has built-in attribute called __name__which python creates and assigns automatically as followsif the file is being run as top-level program file__name__ is set to the string "__main__when it starts if the file is being imported instead__name__ is set to the module' name as known by its clients the upshot is that module can test its own __name__ to determine whether it' being run or imported for examplesuppose we create the following module filenamed runme pyto export single function called testerdef tester()print("it' christmas in heaven "if __name__ ='__main__'tester(only when run not when imported this module defines function for clients to import and use as usualc:\codepython import runme runme tester(it' christmas in heaven but the module also includes code at the bottom that is set up to call the function automatically when this file is run as programc:\codepython runme py it' christmas in heaven in effecta module' __name__ variable serves as usage mode flagallowing its code to be leveraged as both an importable library and top-level script though simpleyou'll see this hook used in the majority of the python program files you are likely to encounter in the wild--both for testing and dual usage for instanceperhaps the most common way you'll see the __name__ test applied is for self-test code in shortyou can package code that tests module' exports in the module itself by wrapping it in __name__ test at the bottom of the file this wayyou can use the file in clients by importing itbut also test its logic by running it from the system shell or via another launching scheme mixed usage modes__name__ and __main__ |
1,312 | common and simplest unit-testing protocol in python it' much more convenient than retyping all your tests at the interactive prompt will discuss other commonly used options for testing python code--as you'll seethe unittest and doctest standard library modules provide more advanced testing tools in additionthe __name__ trick is also commonly used when you're writing files that can be used both as command-line utilities and as tool libraries for instancesuppose you write file-finder script in python you can get more mileage out of your code if you package it in functions and add __name__ test in the file to automatically call those functions when the file is run standalone that waythe script' code becomes reusable in other programs unit tests with __name__ in factwe've already seen prime example in this book of an instance where the __name__ check could be useful in the section on arguments in we coded script that computed the minimum value from the set of arguments sent in (this was the file minmax py in "the min wakeup call!")def minmax(test*args)res args[ for arg in args[ :]if test(argres)res arg return res def lessthan(xy)return def grtrthan(xy)return print(minmax(lessthan )print(minmax(grtrthan )self-test code this script includes self-test code at the bottomso we can test it without having to retype everything at the interactive command line each time we run it the problem with the way it is currently codedhoweveris that the output of the self-test call will appear every time this file is imported from another file to be used as tool--not exactly user-friendly featureto improve itwe can wrap up the self-test call in __name__ checkso that it will be launched only when the file is run as top-level scriptnot when it is imported (this new version of the module file is renamed minmax py here)print(' am:'__name__def minmax(test*args)res args[ for arg in args[ :]if test(argres)res arg return res advanced module topics |
1,313 | def lessthan(xy)return def grtrthan(xy)return if __name__ ='__main__'print(minmax(lessthan )print(minmax(grtrthan )self-test code we're also printing the value of __name__ at the top here to trace its value python creates and assigns this usage-mode variable as soon as it starts loading file when we run this file as top-level scriptits name is set to __main__so its self-test code kicks in automaticallyc:\codepython minmax py am__main__ if we import the filethoughits name is not __main__so we must explicitly call the function to make it runc:\codepython import minmax amminmax minmax minmax(minmax lessthan' '' '' '' ''aagainregardless of whether this is used for testingthe net effect is that we get to use our code in two different roles--as library module of toolsor as an executable program per ' discussion of package relative importsthis section' technique can also have some implications for imports run by files that are also used as package components in xbut can still be leveraged with absolute package path imports and other techniques see the prior discussion and example for more details exampledual mode code here' more substantial module example that demonstrates another way that the prior section' __name__ trick is commonly employed the following moduleformats pydefines string formatting utilities for importersbut also checks its name to see if it is being run as top-level scriptif soit tests and uses arguments listed on the system command line to run canned or passed-in test in pythonthe sys argv list contains command-line arguments--it is list of strings reflecting words typed on the command linewhere the first item is always the name of the script being run we used this in ' benchmark tool as switchesbut leverage it as general input mechanism here#!python ""exampledual mode code |
1,314 | various specialized string display formatting utilities test me with canned self-test or command-line arguments to doadd parens for negative moneyadd more features ""def commas( )""format positive integer-like for display with commas between digit groupings"xxx,yyy,zzz""digits str(nassert(digits isdigit()result 'while digitsdigitslast digits[:- ]digits[- :result (last ',resultif result else last return result def money(nnumwidth= currency='$')""format number for display with commas decimal digitsleading and signand optional padding"-xxx,yyy zznumwidth= for no space paddingcurrency='to omit symboland non-ascii for others ( pound= '\xa or '\ '""sign '-if else ' abs(nwhole commas(int( )fract (' fn)[- :number '% % % (signwholefractreturn '% %* (currencynumwidthnumberif __name__ ='__main__'def selftest()tests fails- tests + tests + * * for test in testsprint(commas(test)print(''tests - tests + tests + * ( * tests + tests +- - - tests +-( * )-( ** tests +( * )-( * for test in testsprint('% [% ](money(test )test)import sys if len(sys argv= selftest( advanced module topics |
1,315 | print(money(float(sys argv[ ])int(sys argv[ ]))this file works identically in python and when run directlyit tests itself as beforebut it uses options on the command line to control the test behavior run this file directly with no command-line arguments on your own to see what its self-test code prints--it' too extensive to list in full herec:\codepython formats py , , , , , etc to test specific stringspass them in on the command line along with minimum field widththe script' __main__ code passes them on to its money functionwhich in turn runs commasc:\codepython formats py $ , , :\codepython formats py - $- , , :\codepython formats py $ , , , , :\codepython formats py - - , , , , :\codepython formats py $ :\codepython formats py - $- as beforebecause this code is instrumented for dual-mode usagewe can also import its tools normally to reuse them as library components in scriptsmodulesand the interactive promptfrom formats import moneycommas money( '$ money(- '- , , '% (% )(commas( ) ' , , , , , , ( )you can use command-line arguments in ways similar to this example to provide general inputs to scripts that may also package their code as functions and classes for reuse by importers for more advanced command-line processingsee "python commandexampledual mode code |
1,316 | parse modulesdocumentation in python' standard library manual in some scenariosyou might also use the built-in input functionused in and to prompt the shell user for test inputs instead of pulling them from the command line also see ' discussion of the new {,dstring format method syntax added in python and this formatting extension separates thousands groups with commas much like the code here the module listed herethoughadds money formattingcan be changedand serves as manual alternative for comma insertions in earlier pythons currency symbolsunicode in action this module' money function defaults to dollarsbut supports other currency symbols by allowing you to pass in non-ascii unicode characters the unicode ordinal with hexadecimal value for exampleis the pound symboland is the yen you can code these in variety of formsasthe character' decoded unicode code point ordinal (integerin text stringwith either unicode or hex escapes (for compatibilityuse leading in such string literals in python the character' raw encoded form in byte string that is decoded before passedwith hex escapes (for compatibilityuse leading in such string literals in python xthe actual character itself in your program' textalong with source code encoding declaration we previewed unicode in and will get into more details in but its basic requirements here are fairly simpleand serve as decent use case to test alternative currenciesi typed the following in fileformats_currency pybecause it was too much to reenter interactively on changesfrom __future__ import print_function from formats import money print(money( )money( '')print(money(xcurrency= '\xa ')money(xcurrency= '\ ')print(money(xcurrency= '\xa decode('latin- '))print(money(xcurrency= '\ ac')money( '\xa decode('iso- - '))print(money(xcurrency= '\xa decode('latin- '))the following gives this test file' output in python in idleand in other contexts configured properly it works the same in because it prints and codes strings portably per __future__ import enables print calls in and as intro advanced module topics |
1,317 | uunicode literals as treated as normal strings in as of $ , , ps , = , ps , eur , eur , $? , if this works on your computeryou can probably skip the next few paragraphs depending on your interface and system settingsthoughgetting this to run and display properly may require additional steps on my machineit behaves correctly when python and the display medium are in syncbut the euro and generic currency symbols in the last two lines fail with errors in basic command prompt on windows specificallythis test script always runs and produces the output shown in the idle gui in both and xbecause unicode-to-glyph mappings are handled well it also works as advertised in on windows if you redirect the output to file and open it with notepadbecause encodes content on this platform in default windows format that notepad understandsc:\codeformats_currency py temp :\codenotepad temp howeverthis doesn' work in xbecause python tries to encode printed text as ascii by default to show all the non-ascii characters in windows command prompt window directlyon some computers you may need to change the windows code page (used to render charactersas well as python' pythonioencoding environment variable (used as the encoding of text in standard streamsincluding the translation of characters to bytes when they are printedto common unicode format such as utf- :\codechcp :\codeset pythonioencoding=utf- :\codeformats_currency py temp :\codetype temp :\codenotepad temp console matches python python matches console both and write utf- text console displays it properly notepad recognizes utf- too you may not need to take these steps on some platforms and even on some windows distributions did because my laptop' code page is set to ( characters)but your code pages may vary subtlythe only reason this test works on python at all is because allows normal and unicode strings to be mixedas long as the normal string is all -bit ascii characters on the uunicode literal is supported for compatibilitybut taken the same as normal stringswhich are always unicode (removing the leading makes the test work in through toobut breaks compatibility) :\codepy - print '\xa ' ''% '\ = ps xunicode/str mix for ascii str :\codepy - exampledual mode code |
1,318 | = ps print('\xa ' ''% '\ ' = ps xstr is unicodeu'optional againthere' much more on unicode in -- topic many see as peripheralbut which can crop up even in relatively simple contexts like thisthe takeaway point here is thatoperational issues asidea carefully coded script can often manage to support unicode in both and docstringsmodule documentation at work finallybecause this example' main file uses the docstring feature introduced in we can use the help function or pydoc' gui/browser modes to explore its tools as well--modules are almost automatically general-purpose tools here' help at workfigure - gives the pydoc view on our file import formats help(formatshelp on module formatsname formats description fileformats py ( and xvarious specialized string display formatting utilities test me with canned self-test or command-line arguments to doadd parens for negative moneyadd more features functions commas(nformat positive integer-like for display with commas between digit groupings"xxx,yyy,zzzmoney(nnumwidth= currency='$'format number for display with commas decimal digitsleading and signand optional padding"-xxx,yyy zznumwidth= for no space paddingcurrency='to omit symboland non-ascii for others ( pound= 'psor 'ps'file :\code\formats py changing the module search path let' return to more general module topics in we learned that the module search path is list of directories that can be customized via the environment variable pythonpathand possibly via pth files what haven' shown you until now is how python program itself can actually change the search path by changing the built-in advanced module topics |
1,319 | in and later and clicking on the file' index entry (see sys path list per sys path is initialized on startupbut thereafter you can deleteappendand reset its components however you likeimport sys sys path [''' :\\temp'' :\\windows\\system \\python zip'more deleted sys path append(' :\\sourcedir'import string extend module search path all imports search the new dir last once you've made such changeit will impact all future imports anywhere while python program runsas all importers share the same single sys path list (there' only one copy of given module in memory during program' run--that' why reload existsin factthis list may be changed arbitrarilysys path [ ' :\temp'sys path append(' :\\lp \\examples'sys path insert( 'sys path ['' :\\temp'' :\\lp \\examples'import string traceback (most recent call last)file ""line in importerrorno module named 'stringchange module search path for this run (processonly thusyou can use this technique to dynamically configure search path inside python program be carefulthoughif you delete critical directory from the pathyou may lose access to critical utilities in the prior examplefor instancewe no longer have changing the module search path |
1,320 | from the pathalsoremember that such sys path settings endure for only as long as the python session or program (technicallyprocessthat made them runsthey are not retained after python exits by contrastpythonpath and pth file path configurations live in the operating system instead of running python programand so are more globalthey are picked up by every program on your machine and live on after program completes on some systemsthe former can be per-user and the latter can be installation-wide the as extension for import and from both the import and from statements were eventually extended to allow an imported name to be given different name in your script we've used this extension earlierbut here are some additional detailsthe following import statementimport modulename as name and use namenot modulename is equivalent to the followingwhich renames the module in the importer' scope only (it' still known by its original name to other files)import modulename name modulename del modulename don' keep original name after such an importyou can--and in fact must--use the name listed after the as to refer to the module this works in from statementtooto assign name imported from file to different name in the importer' scopeas before you get only the new name you providenot its originalfrom modulename import attrname as name and use namenot attrname as discussed in this extension is commonly used to provide short synonyms for longer namesand to avoid name clashes when you are already using name in your script that would otherwise be overwritten by normal import statementimport reallylongmodulename as name name func(use shorter nickname from module import utility as util from module import utility as util util ()util (can have only "utilityit also comes in handy for providing shortsimple name for an entire directory path and avoiding name collisions when using the package import feature described in import dir dir mod as mod mod func(only list full path once from dir dir mod import func as modfunc modfunc(rename to make unique if needed advanced module topics |
1,321 | renames module or tool your code uses extensivelyor provides new alternative you' rather use insteadyou can simply rename it to its prior name on import to avoid breaking your codeimport newname as oldname from library import newname as oldname and keep happily using oldname until you have time to update all your code for examplethis approach can address some library changes ( ' tkinter versus ' tkinter)though they're often substantially more than just new nameexamplemodules are objects because modules expose most of their interesting properties as built-in attributesit' easy to write programs that manage other programs we usually call such manager programs metaprograms because they work on top of other systems this is also referred to as introspectionbecause programs can see and process object internals introspection is somewhat advanced featurebut it can be useful for building programming tools for instanceto get to an attribute called name in module called mwe can use attribute qualification or index the module' attribute dictionaryexposed in the built-in __dict__ attribute we met in python also exports the list of all loaded modules as the sys modules dictionary and provides built-in called getattr that lets us fetch attributes from their string names--it' like saying object attrbut attr is an expression that yields string at runtime because of thatall the following expressions reach the same attribute and object: name __dict__['name'sys modules[' 'name getattr( 'name'qualify object by attribute index namespace dictionary manually index loaded-modules table manually call built-in fetch function by exposing module internals like thispython helps you build programs about programs for examplehere is module named mydir py that puts these ideas to work to implement customized version of the built-in dir function it defines and exports function called listingwhich takes module object as an argument and prints formatted listing of the module' namespace sorted by name as we saw briefly in "other ways to access globalsin because function can access its enclosing module by going through the sys modules table like thisit can also be used to emulate the effect of the global statement for instancethe effect of global xx= can be simulated (albeit with much more typing!by saying this inside functionimport sysglob=sys modules[__name__]glob = remembereach module gets __name__ attribute for freeit' visible as global name inside the functions within the module this trick provides another way to change both local and global variables of the same name inside function examplemodules are objects |
1,322 | ""mydir pya module that lists the namespaces of other modules ""from __future__ import print_function compatibility seplen sepchr '-def listing(moduleverbose=true)sepline sepchr seplen if verboseprint(seplineprint('name:'module __name__'file:'module __file__print(seplinecount for attr in sorted(module __dict__)scan namespace keys (or enumerateprint('% % (countattr)end 'if attr startswith('__')print(''skip __file__etc elseprint(getattr(moduleattr)same as __dict__[attrcount + if verboseprint(seplineprint(module __name__'has % namescountprint(seplineif __name__ ='__main__'import mydir listing(mydirself-test codelist myself notice the docstring at the topas in the prior formats py examplebecause we may want to use this as general toolthe docstring provides functional information accessible via help and gui/browser mode of pydoc-- tool that uses similar introspection tools to do its job self-test is also provided at the bottom of this modulewhich narcissistically imports and lists itself here' the sort of output produced in python this script works on too (where it may list fewer namesbecause it prints from the __future__c:\codepy - mydir py namemydir filec:\code\mydir py __builtins__ __cached__ __doc__ __file__ __initializing__ __loader__ __name__ __package__ advanced module topics |
1,323 | print_function _feature(( 'alpha' )( 'alpha' ) sepchr seplen mydir has names to use this as tool for listing other modulessimply pass the modules in as objects to this file' function here it is listing attributes in the tkinter gui module in the standard library ( tkinter in python )it will technically work on any object with __name____file__and __dict__ attributesimport mydir import tkinter mydir listing(tkinternametkinter filec:\python \lib\tkinter\__init__ py active active all all anchor anchor arc arc at many more names omitted image_types mainloop sys wantobjects warnings tkinter has names we'll meet getattr and its relatives again later the point to notice here is that mydir is program that lets you browse other programs because python exposes its internalsyou can process objects generically importing modules by name string the module name in an import or from statement is hardcoded variable name sometimesthoughyour program will get the name of module to be imported as string at runtime--from user selection in guior parse of an xml documentfor instance unfortunatelyyou can' use import statements directly to load module given its name as string--python expects variable name that' taken literally and not evaluatednot string or expression for instance you can preload tools such as mydir listing and the reloader we'll meet in moment into the interactive namespace by importing them in the file referenced by the pythonstartup environment variable because code in the startup file runs in the interactive namespace (module __main__)importing common tools in the startup file can save you some typing see appendix for more details importing modules by name string |
1,324 | file ""line import "stringsyntaxerrorinvalid syntax it also won' work to simply assign the string to variable namex 'stringimport herepython will try to import file pynot the string module--the name in an import statement both becomes variable assigned to the loaded module and identifies the external file literally running code strings to get around thisyou need to use special tools to load module dynamically from string that is generated at runtime the most general approach is to construct an import statement as string of python code and pass it to the exec built-in function to run (exec is statement in python xbut it can be used exactly as shown here--the parentheses are simply ignored)modname 'stringexec('import modnamerun string of code string imported in this namespace we met the exec function (and its cousin for expressionsevalearlierin and it compiles string of code and passes it to the python interpreter to be executed in pythonthe byte code compiler is available at runtimeso you can write programs that construct and run other programs like this by defaultexec runs the code in the current scopebut you can get more specific by passing in optional namespace dictionaries if needed it also has security issues noted earlier in the bookwhich may be minor in code string you are building yourself direct callstwo options the only real drawback to exec here is that it must compile the import statement each time it runsand compiling can be slow precompiling to byte code with the compile built-in may help for code strings run many timesbut in most cases it' probably simpler and may run quicker to use the built-in __import__ function to load from name string insteadas noted in the effect is similarbut __import__ returns the module objectso assign it to name here to keep itmodname 'stringstring __import__(modnamestring advanced module topics |
1,325 | workand is generally preferred in more recent pythons for direct calls to import by name string--at least per the current "officialpolicy stated in python' manualsimport importlib modname 'stringstring importlib import_module(modnamestring the import_module call takes module name stringand an optional second argument that gives the package used as the anchor point for resolving relative importswhich defaults to none this call works the same as __import__ in its basic rolesbut see python' manuals for more details though both calls still workin pythons where both are availablethe original __import__ is generally intended for customizing import operations by reassignment in the built-in scope (and any future changes in "officialpolicy are beyond the scope of this book!exampletransitive module reloads this section develops module tool that ties together and applies some earlier topicsand serves as larger case study to close out this and part we studied module reloads in as way to pick up changes in code without stopping and restarting program when you reload modulethoughpython reloads only that particular module' fileit doesn' automatically reload modules that the file being reloaded happens to import for exampleif you reload some module aand imports modules and cthe reload applies only to anot to and the statements inside that import and are rerun during the reloadbut they just fetch the already loaded and module objects (assuming they've been imported beforein actual yet abstract codehere' the file pya py import import not reloaded when isjust an import of an already loaded moduleno-ops python from imp import reload reload(aby defaultthis means that you cannot depend on reloads to pick up changes in all the modules in your program transitively--insteadyou must use multiple reload calls to update the subcomponents independently this can require substantial work for large systems you're testing interactively you can design your systems to reload their subcomponents automatically by adding reload calls in parent modules like abut this complicates the modulescode exampletransitive module reloads |
1,326 | better approach is to write general tool to do transitive reloads automatically by scanning modules__dict__ namespace attributes and checking each item' type to find nested modules to reload such utility function could call itself recursively to navigate arbitrarily shaped and deep import dependency chains module __dict__ attributes were introduced in and employed earlier in this and the type call was presented in we just need to combine the two tools the module reloadall py listed next defines reload_all function that automatically reloads moduleevery module that the module importsand so onall the way to the bottom of each import chain it uses dictionary to keep track of already reloaded modulesrecursion to walk the import chainsand the standard library' types modulewhich simply predefines type results for built-in types the visited dictionary technique works to avoid cycles here when imports are recursive or redundantbecause module objects are immutable and so can be dictionary keysas we learned in and set would offer similar functionality if we use visited add(moduleto insert#!python ""reloadall pytransitively reload nested modules ( xcall reload_all with one or more imported module module objects ""import types from imp import reload from required in def status(module)print('reloading module __name__def tryreload(module)tryreload(moduleexceptprint('failed%smoduledef transitive_reload(modulevisited)if not module in visitedstatus(moduletryreload(modulevisited[moduletrue for attrobj in module __dict__ values()if type(attrobj=types moduletypetransitive_reload(attrobjvisiteddef reload_all(*args)visited {for arg in argsif type(arg=types moduletypetransitive_reload(argvisited advanced module topics (only?fails on some trap cyclesduplicates reload this module and visit children for all attrs recur if module main entry point for all passed in |
1,327 | import importlibsys if len(sys argv modname sys argv[ module importlib import_module(modnamereloader(moduleself-test code import on tests only command line (or passedimport by name string test passed-in reloader if __name__ ='__main__'tester(reload_all'reloadall'testreload myselfbesides namespace dictionariesthis script makes use of other tools we've studied hereit includes __name__ test to launch self-test code when run as top-level script onlyand its tester function uses sys argv to inspect command-line arguments and impor tlib to import module by name string passed in as function or command-line argument one curious bitnotice how this code must wrap the basic reload call in try statement to catch exceptions--in python reloads sometimes fail due to rewrite of the import machinery the try was previewed in and is covered in full in part vii testing recursive reloads nowto leverage this utility for normal useimport its reload_all function and pass it an already loaded module object--just as you would for the built-in reload function when the file runs standaloneits self-test code calls reload_all automaticallyreloading its own module by default if no command-line arguments are used in this modethe module must import itself because its own name is not defined in the file without an import this code works in both and because we've used and instead of comma in the printsthough the set of modules used and thus reloaded may vary across linesc:\codec:\python \python reloadall py reloading reloadall reloading types :\codec:\python \python reloadall py reloading reloadall reloading types with command-line argumentthe tester instead reloads the given module by its name string--herethe benchmark module we coded in note that we give module name in this modenot filename (as for import statementsdon' include the py extension)the script ultimately imports the module using the module search path as usualc:\codereloadall py pybench reloading pybench reloading timeit reloading itertools reloading sys reloading time reloading gc reloading os exampletransitive module reloads |
1,328 | reloading ntpath reloading stat reloading genericpath reloading copyreg perhaps most commonlywe can also deploy this module at the interactive prompt-herein for some standard library modules notice how os is imported by tkinterbut tkinter reaches sys before os can (if you want to test this on python xsubstitute tkinter for tkinter)from reloadall import reload_all import ostkinter reload_all(osreloading os reloading ntpath reloading stat reloading sys reloading genericpath reloading errno reloading copyreg normal usage mode reload_all(tkinterreloading tkinter reloading _tkinter reloading warnings reloading sys reloading linecache reloading tokenize reloading builtins failedreloading re etc reloading os reloading ntpath reloading stat reloading genericpath reloading errno etc and finally here is session that shows the effect of normal versus transitive reloads-changes made to the two nested files are not picked up by reloadsunless the transitive utility is usedimport file py import file py file py :\codepy - import xa ya advanced module topics |
1,329 | without stopping pythonchange all three filesassignment values and save from imp import reload reload(aa xa ya ( from reloadall import reload_all reload_all(areloading reloading reloading xa ya ( built-in reload is top level only normal usage mode reloads all nested modules too study the reloader' code and results for more on its operation the next section exercises its tools further alternative codings for all the recursion fans in the audiencethe following lists an alternative recursive coding for the function in the prior section--it uses set instead of dictionary to detect cyclesis marginally more direct because it eliminates top-level loopand serves to illustrate recursive function techniques in general (compare with the original to see how this differsthis version also gets some of its work for free from the originalthough the order in which it reloads modules might vary if namespace dictionary order does too""reloadall pytransitively reload nested modules (alternative coding""import types from imp import reload from reloadall import statustryreloadtester from required in def transitive_reload(objectsvisited)for obj in objectsif type(obj=types moduletype and obj not in visitedstatus(objtryreload(objreload thisrecur to attrs visited add(objtransitive_reload(obj __dict__ values()visiteddef reload_all(*args)transitive_reload(argsset()if __name__ ='__main__'tester(reload_all'reloadall 'test codereload myselfexampletransitive module reloads |
1,330 | recursive functionswhich may be preferable in some contexts the following is one such transitive reloaderit uses generator expression to filter out nonmodules and modules already visited in the current module' namespace because it both pops and adds items at the end of its listit is stack basedthough the order of both pushes and dictionary values influences the order in which it reaches and reloads modules--it visits submodules in namespace dictionaries from right to leftunlike the left-to-right order of the recursive versions (trace through the code to see howwe could change thisbut dictionary order is arbitrary anyhow ""reloadall pytransitively reload nested modules (explicit stack""import types from imp import reload from reloadall import statustryreloadtester from required in def transitive_reload(modulesvisited)while modulesnext modules pop(delete next item at end status(nextreload thispush attrs tryreload(nextvisited add(nextmodules extend( for in next __dict__ values(if type( =types moduletype and not in visiteddef reload_all(*modules)transitive_reload(list(modules)set()if __name__ ='__main__'tester(reload_all'reloadall 'test codereload myselfif the recursion and nonrecursion used in this example is confusingsee the discussion of recursive functions in for background on the subject testing reload variants to prove that these work the samelet' test all three of our reloader variants thanks to their common testing functionwe can run all three from command line both with no arguments to test the module reloading itselfand with the name of module to be reloaded listed on the command line (in sys argv) :\codereloadall py reloading reloadall reloading types :\codereloadall py reloading reloadall reloading types :\codereloadall py advanced module topics |
1,331 | reloading types though it' hard to see herewe really are testing the individual reloader alternatives --each of these tests shares common tester functionbut passes it the reload_all from its own file here are the variants reloading the tkinter gui module and all the modules its imports reachc:\codereloadall py tkinter reloading tkinter reloading _tkinter reloading tkinter _fix etc :\codereloadall py tkinter reloading tkinter reloading tkinter constants reloading tkinter _fix etc :\codereloadall py tkinter reloading tkinter reloading sys reloading tkinter constants etc all three work on both python and too--they're careful to unify prints with formattingand avoid using version-specific tools (though you must use module names like tkinterand ' using the windows launcher here to run per appendix ) :\codepy - reloadall py reloading reloadall reloading types :\codepy - reloadall py tkinter reloading tkinter reloading _tkinter reloading fixtk etc as usual we can test interactivelytooby importing and calling either module' main reload entry point with module objector the testing function with reloader function and module name stringc:\codepy - import reloadallreloadall reloadall import tkinter reloadall reload_all(tkinterreloading tkinter reloading tkinter _fix reloading os etc reloadall tester(reloadall reload_all'tkinter'reloading tkinter reloading tkinter _fix reloading os normal use case testing utility exampletransitive module reloads |
1,332 | reloadall tester(reloadall reload_all'reloadall 'reloading reloadall reloading types mimic self-test code finallyif you look at the output of tkinter reloads earlieryou may notice that each of the three variants may produce results in different orderthey all depend on namespace dictionary orderingand the last also relies on the order in which items are added to its stack in factunder python the reload order for given reloader can vary from run to run to ensure that all three are reloading the same modules irrespective of the order in which they do sowe can use sets (or sortsto test for order-neutral equality of their printed messages--obtained here by running shell commands with the os popen utility we met in and used in import os res os popen('reloadall py tkinter'read(res os popen('reloadall py tkinter'read(res os popen('reloadall py tkinter'read(res [: 'reloading tkinter\nreloading tkinter constants\nreloading tkinter _fix\nreloadres =res res =res (falsefalseset(res =set(res )set(res =set(res (truetruerun these scriptsstudy their codeand experiment on your own for more insightthese are the sort of importable tools you might want to add to your own source code library watch for similar testing technique in the coverage of class tree listers in where we'll apply it to passed class objects and extend it further also keep in mind that all three variants reload only modules that were loaded with import statements--since names copied with from statements do not cause module to be nested and referenced in the importer' namespacetheir containing module is not reloaded more fundamentallythe transitive reloaders rely on the fact that module reloads update module objects in placesuch that all references to those modules in any scope will see the updated version automatically because they copy names outfrom importers are not updated by reloads--transitive or not--and supporting this may require either source code analysisor customization of the import operation (see for pointerstool impacts like this are perhaps another reason to prefer import to from--which brings us to the end of this and partand the standard set of warnings for this part' topic module gotchas in this sectionwe'll take look at the usual collection of boundary cases that can make life interesting for python beginners some are review hereand few are so obscure advanced module topics |
1,333 | something important about the language module name clashespackage and package-relative imports if you have two modules of the same nameyou may only be able to import one of them --by defaultthe one whose directory is leftmost in the sys path module search path will always be chosen this isn' an issue if the module you prefer is in your top-level script' directorysince that is always first in the module pathits contents will be located first automatically for cross-directory importshoweverthe linear nature of the module search path means that same-named files can clash to fixeither avoid same-named files or use the package imports feature of if you need to get to both same-named filesstructure your source files in subdirectoriessuch that package import directory names make the module references unique as long as the enclosing package directory names are uniqueyou'll be able to access either or both of the same-named modules note that this issue can also crop up if you accidentally use name for module of your own that happens to be the same as standard library module you need--your local module in the program' home directory (or another directory early in the module pathcan hide and replace the library module to fixeither avoid using the same name as another module you need or store your modules in package directory and use python ' package-relative import modelavailable in as an option in this modelnormal imports skip the package directory (so you'll get the library' version)but special dotted import statements can still select the local version of the module if needed statement order matters in top-level code as we've seenwhen module is first imported (or reloaded)python executes its statements one by onefrom the top of the file to the bottom this has few subtle implications regarding forward references that are worth underscoring herecode at the top level of module file (not nested in functionruns as soon as python reaches it during an importbecause of thatit cannot reference names assigned lower in the file code inside function body doesn' run until the function is calledbecause names in function aren' resolved until the function actually runsthey can usually reference names anywhere in the file generallyforward references are only concern in top-level module code that executes immediatelyfunctions can reference names arbitrarily here' file that illustrates forward reference dos and don'tsmodule gotchas |
1,334 | error"func not yet assigned def func ()print(func ()ok"func looked up later func (error"func not yet assigned def func ()return "hellofunc (ok"func and "func assigned when this file is imported (or run as standalone program)python executes its statements from top to bottom the first call to func fails because the func def hasn' run yet the call to func inside func works as long as func ' def has been reached by the time func is called--and it hasn' when the second top-level func call is run the last call to func at the bottom of the file works because func and func have both been assigned mixing defs with top-level code is not only difficult to readit' also dependent on statement ordering as rule of thumbif you need to mix immediate code with defsput your defs at the top of the file and your top-level code at the bottom that wayyour functions are guaranteed to be defined and assigned by the time python runs the code that uses them from copies names but doesn' link although it' commonly usedthe from statement is the source of variety of potential gotchas in python as we've learnedthe from statement is really an assignment to names in the importer' scope-- name-copy operationnot name aliasing the implications of this are the same as for all assignments in pythonbut they're subtleespecially given that the code that shares the objects lives in different files for instancesuppose we define the following modulenested pynested py def printer()print(xif we import its two names using from in another modulenested pywe get copies of those namesnot links to them changing name in the importer resets only the binding of the local version of that namenot the name in nested pynested py from nested import xprinter printer(python nested py advanced module topics copy names out changes my "xonlynested ' is still |
1,335 | we change the name in nested py attribute qualification directs python to name in the module objectrather than name in the importernested pynested py import nested nested nested printer(get module as whole okchange nested ' python nested py from can obscure the meaning of variables mentioned this earlier but saved the details for here because you don' list the variables you want when using the from module import statement formit can accidentally overwrite names you're already using in your scope worseit can make it difficult to determine where variable comes from this is especially true if the from form is used on more than one imported file for exampleif you use from on three modules in the followingyou'll have no way of knowing what raw function call really meansshort of searching all three external module files--all of which may be in other directoriesfrom module import from module import from module import badmay overwrite my names silently worseno way to tell what we getfunc(huh??the solution again is not to do thistry to explicitly list the attributes you want in your from statementsand restrict the from form to at most one imported module per file that wayany undefined names must by deduction be in the module named in the single from you can avoid the issue altogether if you always use import instead of frombut that advice is too harshlike much else in programmingfrom is convenient tool if used wisely even this example isn' an absolute evil--it' ok for program to use this technique to collect names in single space for convenienceas long as it' well known reload may not impact from imports here' another from-related gotchaas discussed previouslybecause from copies (assignsnames when runthere' no link back to the modules where the names came from names imported with from simply become references to objectswhich happen to have been referenced by the same names in the importee when the from ran module gotchas |
1,336 | names using from that isthe client' names will still reference the original objects fetched with fromeven if the names in the original module are later resetfrom module import from imp import reload reload(modulex may not reflect any module reloadschanges modulebut not my names still references old object to make reloads more effectiveuse import and name qualification instead of from because qualifications always go back to the modulethey will find the new bindings of module names after reloading has updated the module' content in placeimport module from imp import reload reload(modulemodule get modulenot names changes module in place get current xreflects module reloads as related consequenceour transitive reloader earlier in this doesn' apply to names fetched with fromonly importagainif you're going to use reloadsyou're probably better off with import reloadfromand interactive testing in factthe prior gotcha is even more subtle than it appears warned that it' usually better not to launch programs with imports and reloads because of the complexities involved things get even worse when from is brought into the mix python beginners most often stumble onto its issues in scenarios like this--imagine that after opening module file in text edit windowyou launch an interactive session to load and test your module with fromfrom module import function function( finding bugyou jump back to the edit windowmake changeand try to reload the module this wayfrom imp import reload reload(modulethis doesn' workbecause the from statement assigned only the name functionnot module to refer to the module in reloadyou have to first bind its name with an import statement at least oncefrom imp import reload import module reload(modulefunction( howeverthis doesn' quite work either--reload updates the module object in placebut as discussed in the preceding sectionnames like function that were copied out of advanced module topics |
1,337 | original version of the function to really get the new functionyou must refer to it as module function after the reloador rerun the fromfrom imp import reload import module reload(modulefrom module import function function( or give up and use module function(nowthe new version of the function will finally runbut it seems an awful lot of work to get there as you can seethere are problems inherent in using reload with fromnot only do you have to remember to reload after importsbut you also have to remember to rerun your from statements after reloads this is complex enough to trip up even an expert once in while in factthe situation has gotten even worse in python xbecause you must also remember to import reload itselfthe short story is that you should not expect reload and from to play together nicely againthe best policy is not to combine them at all--use reload with importor launch your programs other waysas suggested in using the run-run module menu option in idlefile icon clickssystem command linesor the exec built-in function recursive from imports may not work saved the most bizarre (andthankfullyobscuregotcha for last because imports execute file' statements from top to bottomyou need to be careful when using modules that import each other this is often called recursive importsbut the recursion doesn' really occur (in factcircular may be better term here)--such imports won' get stuck in infinite importing loops stillbecause the statements in module may not all have been run when it imports another modulesome of its names may not yet exist if you use import to fetch the module as wholethis probably doesn' matterthe module' names won' be accessed until you later use qualification to fetch their valuesand by that time the module is likely complete but if you use from to fetch specific namesyou must bear in mind that you will only have access to names in that module that have already been assigned when recursive import is kicked off for instanceconsider the following modulesrecur and recur recur assigns name xand then imports recur before assigning the name at this pointrecur can fetch recur as whole with an import--it already exists in python' internal modules tablewhich makes it importableand also prevents the imports from looping but if recur uses fromit will be able to see only the name xthe name ywhich is assigned below the import in recur doesn' yet existso you get an errorrecur py module gotchas |
1,338 | recur py from recur import from recur import run recur now if it doesn' exist ok"xalready assigned error"ynot yet assigned :\codepy - import recur traceback (most recent call last)file ""line in file \recur py"line in import recur file \recur py"line in from recur import importerrorcannot import name python avoids rerunning recur ' statements when they are imported recursively from recur (otherwise the imports would send the script into an infinite loop that might require ctrl- solution or worse)but recur ' namespace is incomplete when it' imported by recur the solutiondon' use from in recursive imports (noreally!python won' get stuck in cycle if you dobut your programs will once again be dependent on the order of the statements in the modules in factthere are two ways out of this gotchayou can usually eliminate import cycles like this by careful design--maximizing cohesion and minimizing coupling are good first steps if you can' break the cycles completelypostpone module name accesses by using import and attribute qualification (instead of from and direct names)or by running your froms either inside functions (instead of at the top level of the moduleor near the bottom of your file to defer their execution there is additional perspective on this issue in the exercises at the end of this --which we've officially reached summary this surveyed some more advanced module-related concepts we studied data hiding techniquesenabling new language features with the __future__ modulethe __name__ usage mode variabletransitive reloadsimporting by name stringsand more we also explored and summarized module design issueswrote some more substantial programsand looked at common mistakes related to modules to help you avoid them in your code the next begins our look at python' class--its object-oriented programming tool much of what we've covered in the last few will apply theretooclasses live in modules and are namespaces as wellbut they add an extra component to attribute lookup called inheritance search as this is the last in this part of the advanced module topics |
1,339 | bookhoweverbefore we dive into that topicbe sure to work through this part' set of lab exercises and before thathere is this quiz to review the topics covered here test your knowledgequiz what is significant about variables at the top level of module whose names begin with single underscore what does it mean when module' __name__ variable is the string "__main__" if the user interactively types the name of module to testhow can your code import it how is changing sys path different from setting pythonpath to modify the module search path if the module __future__ allows us to import from the futurecan we also import from the pasttest your knowledgeanswers variables at the top level of module whose names begin with single underscore are not copied out to the importing scope when the from statement form is used they can still be accessed by an import or the normal from statement formthough the __all__ list is similarbut the logical converseits contents are the only names that are copied out on from if module' __name__ variable is the string "__main__"it means that the file is being executed as top-level script instead of being imported from another file in the program that isthe file is being used as programnot library this usage mode variable supports dual-mode code and tests user input usually comes into script as stringto import the referenced module given its string nameyou can build and run an import statement with execor pass the string name in call to the __import__ or importlib import_module changing sys path only affects one running program (process)and is temporary --the change goes away when the program ends pythonpath settings live in the operating system--they are picked up globally by all your programs on machineand changes to these settings endure after programs exit nowe can' import from the past in python we can install (or stubbornly usean older version of the languagebut the latest python is generally the best python (at least within lines--see longevity!test your knowledgeanswers |
1,340 | see part in appendix for the solutions import basics write program that counts the lines and characters in file (similar in spirit to part of what wc does on unixwith your text editorcode python module called mymod py that exports three top-level namesa countlines(namefunction that reads an input file and counts the number of lines in it (hintfile readlines does most of the work for youand len does the restthough you could count with for and file iterators to support massive files tooa countchars(namefunction that reads an input file and counts the number of characters in it (hintfile read returns single stringwhich may be used in similar waysa test(namefunction that calls both counting functions with given input filename such filename generally might be passed inhardcodedinput with the input built-in functionor pulled from command line via the sys argv list shown in this formats py and reloadall py examplesfor nowyou can assume it' passed-in function argument all three mymod functions should expect filename string to be passed in if you type more than two or three lines per functionyou're working much too hard-use the hints just gavenexttest your module interactivelyusing import and attribute references to fetch your exports does your pythonpath need to include the directory where you created mymod pytry running your module on itselffor exampletest("mymod py"note that test opens the file twiceif you're feeling ambitiousyou may be able to improve this by passing an open file object into the two count functions (hintfile seek( is file rewind from/from test your mymod module from exercise interactively by using from to load the exports directlyfirst by namethen using the from variant to fetch everything __main__ add line in your mymod module that calls the test function automatically only when the module is run as scriptnot when it is imported the line you add will probably test the value of __name__ for the string "__main__"as shown in this try running your module from the system command linethenimport the module and test its functions interactively does it still work in both modes nested imports write second modulemyclient pythat imports mymod and tests its functionsthen run myclient from the system command line if myclient uses from to fetch from mymodwill mymod' functions be accessible from the top level of myclientwhat if it imports with import insteadtry coding both variations in advanced module topics |
1,341 | attribute package imports import your file from package create subdirectory called mypkg nested in directory on your module import search pathcopy or move the mymod py module file you created in exercise or into the new directoryand try to import it with package import of the form import mypkg mymod and call its functions try to fetch your counter functions with from too you'll need to add an __init__ py file in the directory your module was moved to make this gobut it should work on all major python platforms (that' part of the reason python uses as path separatorthe package directory you create can be simply subdirectory of the one you're working inif it isit will be found via the home directory component of the search pathand you won' have to configure your path add some code to your __init__ pyand see if it runs on each import reloads experiment with module reloadsperform the tests in ' changer py examplechanging the called function' message and/or behavior repeatedlywithout stopping the python interpreter depending on your systemyou might be able to edit changer in another windowor suspend the python interpreter and edit in the same window (on unixa ctrl- key combination usually suspends the current processand an fg command later resumes itthough text edit window probably works just as well circular imports in the section on recursive ( circularimport gotchasimporting recur raised an error but if you restart python and import recur interactivelythe error doesn' occur--test this and see for yourself why do you think it works to import recur but not recur (hintpython stores new modules in the built-in sys modules table-- dictionary--before running their codelater imports fetch the module from this table firstwhether the module is "completeyet or not nowtry running recur as top-level script filepython recur py do you get the same error that occurs when recur is imported interactivelywhy(hintwhen modules are run as programsthey aren' importedso this case has the same effect as importing recur interactivelyrecur is the first module imported what happens when you run recur as scriptcircular imports are uncommon and rarely this bizarre in practice on the other handif you can understand why they are potential problemyou know lot about python' import semantics test your knowledgepart exercises |
1,342 | classes and oop |
1,343 | oopthe big picture so far in this bookwe've been using the term "objectgenerically reallythe code written up to this point has been object-based--we've passed objects around our scriptsused them in expressionscalled their methodsand so on for our code to qualify as being truly object-oriented (oo)thoughour objects will generally need to also participate in something called an inheritance hierarchy this begins our exploration of the python class-- coding structure and device used to implement new kinds of objects in python that support inheritance classes are python' main object-oriented programming (ooptoolso we'll also look at oop basics along the way in this part of the book oop offers different and often more effective way of programmingin which we factor code to minimize redundancyand write new programs by customizing existing code instead of changing it in place in pythonclasses are created with new statementthe class as you'll seethe objects defined with classes can look lot like the built-in types we studied earlier in the book in factclasses really just apply and extend the ideas we've already coveredroughlythey are packages of functions that use and process built-in object types classesthoughare designed to create and manage new objectsand support inheritance-- mechanism of code customization and reuse above and beyond anything we've seen so far one note up frontin pythonoop is entirely optionaland you don' need to use classes just to get started you can get plenty of work done with simpler constructs such as functionsor even simple top-level script code because using classes well requires some up-front planningthey tend to be of more interest to people who work in strategic mode (doing long-term product developmentthan to people who work in tactical mode (where time is in very short supplystillas you'll see in this part of the bookclasses turn out to be one of the most useful tools python provides when used wellclasses can actually cut development time radically they're also employed in popular python tools like the tkinter gui apiso most python programmers will usually find at least working knowledge of class basics helpful |
1,344 | remember when told you that programs "do things with stuffin and in simple termsclasses are just way to define new sorts of stuffreflecting real objects in program' domain for instancesuppose we decide to implement that hypothetical pizza-making robot we used as an example in if we implement it using classeswe can model more of its real-world structure and relationships two aspects of oop prove useful hereinheritance pizza-making robots are kinds of robotsso they possess the usual robot- properties in oop termswe say they "inheritproperties from the general category of all robots these common properties need to be implemented only once for the general case and can be reused in part or in full by all types of robots we may build in the future composition pizza-making robots are really collections of components that work together as team for instancefor our robot to be successfulit might need arms to roll doughmotors to maneuver to the ovenand so on in oop parlanceour robot is an example of compositionit contains other objects that it activates to do its bidding each component might be coded as classwhich defines its own behavior and relationships general oop ideas like inheritance and composition apply to any application that can be decomposed into set of objects for examplein typical gui systemsinterfaces are written as collections of widgets--buttonslabelsand so on--which are all drawn when their container is drawn (compositionmoreoverwe may be able to write our own custom widgets--buttons with unique fontslabels with new color schemesand the like--which are specialized versions of more general interface devices (inheritancefrom more concrete programming perspectiveclasses are python program unitsjust like functions and modulesthey are another compartment for packaging logic and data in factclasses also define new namespacesmuch like modules butcompared to other program units we've already seenclasses have three critical distinctions that make them more useful when it comes to building new objectsmultiple instances classes are essentially factories for generating one or more objects every time we call classwe generate new object with distinct namespace each object generated from class has access to the class' attributes and gets namespace of its own for data that varies per object this is similar to the per-call state retention of ' closure functionsbut is explicit and natural in classesand is just one of the things that classes do classes offer complete programming solution oopthe big picture |
1,345 | classes also support the oop notion of inheritancewe can extend class by redefining its attributes outside the class itself in new software components coded as subclasses more generallyclasses can build up namespace hierarchieswhich define names to be used by objects created from classes in the hierarchy this supports multiple customizable behaviors more directly than other tools operator overloading by providing special protocol methodsclasses can define objects that respond to the sorts of operations we saw at work on built-in types for instanceobjects made with classes can be slicedconcatenatedindexedand so on python provides hooks that classes can use to intercept and implement any built-in type operation at its basethe mechanism of oop in python is largely just two bits of magica special first argument in functions (to receive the subject of calland inheritance attribute search (to support programming by customizationother than thisthe model is largely just functions that ultimately process built-in types while not radically newthoughoop adds an extra layer of structure that supports better programming than flat procedural models along with the functional tools we met earlierit represents major abstraction step above computer hardware that helps us build more sophisticated programs oop from , feet before we see what this all means in terms of codei' like to say few words about the general ideas behind oop if you've never done anything object-oriented in your life before nowsome of the terminology in this may seem bit perplexing on the first pass moreoverthe motivation for these terms may be elusive until you've had chance to study the ways that programmers apply them in larger systems oop is as much an experience as technology attribute inheritance search the good news is that oop is much simpler to understand and use in python than in other languagessuch as +or java as dynamically typed scripting languagepython removes much of the syntactic clutter and complexity that clouds oop in other tools in factmuch of the oop story in python boils down to this expressionobject attribute we've been using this expression throughout the book to access module attributescall methods of objectsand so on when we say this to an object that is derived from class statementhoweverthe expression kicks off search in python--it searches tree of linked objectslooking for the first appearance of attribute that it can find when classes are involvedthe preceding python expression effectively translates to the following in natural languageoop from , feet |
1,346 | from bottom to top and left to right in other wordsattribute fetches are simply tree searches the term inheritance is applied because objects lower in tree inherit attributes attached to objects higher in that tree as the search proceeds from the bottom upin sensethe objects linked into tree are the union of all the attributes defined in all their tree parentsall the way up the tree in pythonthis is all very literalwe really do build up trees of linked objects with codeand python really does climb this tree at runtime searching for attributes every time we use the object attribute expression to make this more concretefigure - sketches an example of one of these trees figure - class treewith two instances at the bottom ( and ) class above them ( )and two superclasses at the top ( and all of these objects are namespaces (packages of variables)and the inheritance search is simply search of the tree from bottom to top looking for the lowest occurrence of an attribute name code implies the shape of such trees in this figurethere is tree of five objects labeled with variablesall of which have attached attributesready to be searched more specificallythis tree links together three class objects (the ovals and and two instance objects (the rectangles and into an inheritance search tree notice that in the python object modelclasses and the instances you generate from them are two distinct object typesclasses serve as instance factories their attributes provide behavior--data and functions --that is inherited by all the instances generated from them ( function to compute an employee' salary from pay and hoursinstances represent the concrete items in program' domain their attributes record data that varies per specific object ( an employee' social security numberin terms of search treesan instance inherits attributes from its classand class inherits attributes from all classes above it in the tree oopthe big picture |
1,347 | we usually call classes higher in the tree (like and superclassesclasses lower in the tree (like are known as subclasses these terms refer to both relative tree positions and roles superclasses provide behavior shared by all their subclassesbut because the search proceeds from the bottom upsubclasses may override behavior defined in their superclasses by redefining superclass names lower in the tree as these last few words are really the crux of the matter of software customization in ooplet' expand on this concept suppose we build up the tree in figure - and then say thisi right awaythis code invokes inheritance because this is an object attribute expressionit triggers search of the tree in figure - --python will search for the attribute by looking in and above specificallyit will search the linked objects in this orderi and stop at the first attached it finds (or raise an error if isn' found at allin this casew won' be found until is searched because it appears only in that object in other wordsi resolves to by virtue of the automatic search in oop terminologyi "inheritsthe attribute from ultimatelythe two instances inherit four attributes from their classeswxyand other attribute references will wind up following different paths in the tree for examplei and both find in and stop because is lower than and both find in because that' the only place appears and both find in because is further to the left than name finds name in without climbing the tree at all trace these searches through the tree in figure - to get feel for how inheritance searches work in python the first item in the preceding list is perhaps the most important to notice--because redefines the attribute lower in the treeit effectively replaces the version above it in as you'll see in momentsuch redefinitions are at the heart of software customization in oop--by redefining and replacing the attributec effectively customizes what it inherits from its superclasses in other literature and circlesyou may also occasionally see the terms base classes and derived classes used to describe superclasses and subclassesrespectively python people and this book tend to use the latter terms oop from , feet |
1,348 | although they are technically two separate object types in the python modelthe classes and instances we put in these trees are almost identical--each type' main purpose is to serve as another kind of namespace-- package of variablesand place where we can attach attributes if classes and instances therefore sound like modulesthey shouldhoweverthe objects in class trees also have automatically searched links to other namespace objectsand classes correspond to statementsnot entire files the primary difference between classes and instances is that classes are kind of factory for generating instances for examplein realistic applicationwe might have an employee class that defines what it means to be an employeefrom that classwe generate actual employee instances this is another difference between classes and modules-we only ever have one instance of given module in memory (that' why we have to reload module to get its new code)but with classeswe can make as many instances as we need operationallyclasses will usually have functions attached to them ( computesa lary)and the instances will have more basic data items used by the class' functions ( hoursworkedin factthe object-oriented model is not that different from the classic data-processing model of programs plus records--in oopinstances are like records with "data,and classes are the "programsfor processing those records in oopthoughwe also have the notion of an inheritance hierarchywhich supports software customization better than earlier models method calls in the prior sectionwe saw how the attribute reference in our example class tree was translated to by the inheritance search procedure in python perhaps just as important to understand as the inheritance of attributesthoughis what happens when we try to call methods--functions attached to classes as attributes if this reference is function callwhat it really means is "call the function to process that ispython will automatically map the call (into the call ( )passing in the instance as the first argument to the inherited function in factwhenever we call function attached to class in this fashionan instance of the class is always implied this implied subject or context is part of the reason we refer to this as an object-oriented model--there is always subject object when an operation is run in more realistic examplewe might invoke method called giveraise attached as an attribute to an employee classsuch call has no meaning unless qualified with the employee to whom the raise should be given as we'll see laterpython passes in the implied instance to special first argument in the methodcalled self by convention methods go through this argument to process the subject of the call as we'll also learnmethods can be called through either an instance--bob giveraise()--or class--employee giveraise(bob)--and both forms oopthe big picture |
1,349 | to run bob giveraise(method callpython looks up giveraise from bobby inheritance search passes bob to the located giveraise functionin the special self argument when you call employee giveraise(bob)you're just performing both steps yourself this description is technically the default case (python has additional method types we'll meet later)but it applies to the vast majority of the oop code written in the language to see how methods receive their subjectsthoughwe need to move on to some code coding class trees although we are speaking in the abstract herethere is tangible code behind all these ideasof course we construct trees and their objects with class statements and class callswhich we'll meet in more detail later in shorteach class statement generates new class object each time class is calledit generates new instance object instances are automatically linked to the classes from which they are created classes are automatically linked to their superclasses according to the way we list them in parentheses in class header linethe left-to-right order there gives the order in the tree to build the tree in figure - for examplewe would run python code of the following form like function definitionclasses are normally coded in module files and are run during an import ( 've omitted the guts of the class statements here for brevity)class class class ( )make class objects (ovalsi ( (make instance objects (rectangleslinked to their classes linked to superclasses (in this orderherewe build the three class objects by running three class statementsand make the two instance objects by calling the class twiceas though it were function the instances remember the class they were made fromand the class remembers its listed superclasses technicallythis example is using something called multiple inheritancewhich simply means that class has more than one superclass above it in the class tree-- useful technique when you wish to combine multiple tools in pythonif there is more than one superclass listed in parentheses in class statement (like ' here)their left-toright order gives the order in which those superclasses will be searched for attributes oop from , feet |
1,350 | choose name by asking for it from the class it lives in ( zbecause of the way inheritance searches proceedthe object to which you attach an attribute turns out to be crucial--it determines the name' scope attributes attached to instances pertain only to those single instancesbut attributes attached to classes are shared by all their subclasses and instances laterwe'll study the code that hangs attributes on these objects in depth as we'll findattributes are usually attached to classes by assignments made at the top level in class statement blocksand not nested inside function def statements there attributes are usually attached to instances by assignments to the special argument passed to functions coded inside classescalled self for exampleclasses provide behavior for their instances with method functions we create by coding def statements inside class statements because such nested defs assign names within the classthey wind up attaching attributes to the class object that will be inherited by all instances and subclassesclass class make superclass objects class ( )def setname(selfwho)self name who make and link class assign namec setname self is either or ( ( setname('bob' setname('sue'print( namemake two instances sets name to 'bobsets name to 'sueprints 'bobthere' nothing syntactically unique about def in this context operationallythoughwhen def appears inside class like thisit is usually known as methodand it automatically receives special first argument--called self by convention--that provides handle back to the instance to be processed any values you pass to the method yourself go to arguments after self (hereto who because classes are factories for multiple instancestheir methods usually go through this automatically passed-in self argument whenever they need to fetch or set attributes of the particular instance being processed by method call in the preceding codeself is used to store name in one of two instances like simple variablesattributes of classes and instances are not declared ahead of timebut spring into existence the first time they are assigned values when method assigns to self attributeit creates or changes an attribute in an instance at the bottom of the if you've ever used +or javayou'll recognize that python' self is the same as the this pointerbut self is always explicit in both headers and bodies of python methods to make attribute accesses more obviousa name has fewer possible meanings oopthe big picture |
1,351 | to the instance being processed--the subject of the call in factbecause all the objects in class trees are just namespace objectswe can fetch or set any of their attributes by going through the appropriate names saying setname is as valid as saying setnameas long as the names and are in your code' scopes operator overloading as currently codedour class doesn' attach name attribute to an instance until the setname method is called indeedreferencing name before calling setname would produce an undefined name error if class wants to guarantee that an attribute like name is always set in its instancesit more typically will fill out the attribute at construction timelike thisclass class make superclass objects class ( )def __init__(selfwho)self name who set name when constructed self is either or ('bob' ('sue'print( namesets name to 'bobsets name to 'sueprints 'bobif it' coded or inheritedpython automatically calls method named __init__ each time an instance is generated from class the new instance is passed in to the self argument of __init__ as usualand any values listed in parentheses in the class call go to arguments two and beyond the effect here is to initialize instances when they are madewithout requiring extra method calls the __init__ method is known as the constructor because of when it is run it' the most commonly used representative of larger class of methods called operator overloading methodswhich we'll discuss in more detail in the that follow such methods are inherited in class trees as usual and have double underscores at the start and end of their names to make them distinct python runs them automatically when instances that support them appear in the corresponding operationsand they are mostly an alternative to using simple method calls they're also optionalif omittedthe operations are not supported if no __init__ is presentclass calls return an empty instancewithout initializing it for exampleto implement set intersectiona class might either provide method named intersector overload the expression operator to dispatch to the required logic by coding method named __and__ because the operator scheme makes instances look and feel more like built-in typesit allows some classes to provide consistent and natural interfaceand be compatible with code that expects built-in type stillapart from the __init__ constructor--which appears in most realistic classes--many prooop from , feet |
1,352 | to built-ins giveraise may make sense for an employeebut might not oop is about code reuse and thatalong with few syntax detailsis most of the oop story in python of coursethere' bit more to it than just inheritance for exampleoperator overloading is much more general than 've described so far--classes may also provide their own implementations of operations such as indexingfetching attributesprintingand more by and largethoughoop is about looking up attributes in trees with special first argument in functions so why would we be interested in building and searching trees of objectsalthough it takes some experience to see howwhen used wellclasses support code reuse in ways that other python program components cannot in factthis is their highest purpose with classeswe code by customizing existing softwareinstead of either changing existing code in place or starting from scratch for each new project this turns out to be powerful paradigm in realistic programming at fundamental levelclasses are really just packages of functions and other namesmuch like modules howeverthe automatic attribute inheritance search that we get with classes supports customization of software above and beyond what we can do with modules and functions moreoverclasses provide natural structure for code that packages and localizes logic and namesand so aids in debugging for instancebecause methods are simply functions with special first argumentwe can mimic some of their behavior by manually passing objects to be processed to simple functions the participation of methods in class inheritancethoughallows us to naturally customize existing software by coding subclasses with new method definitionsrather than changing existing code in place there is really no such concept with modules and functions polymorphism and classes as an examplesuppose you're assigned the task of implementing an employee database application as python oop programmeryou might begin by coding general superclass that defines default behaviors common to all the kinds of employees in your organizationclass employeedef computesalary(self)def giveraise(self)def promote(self)def retire(self)general superclass common or default behaviors once you've coded this general behavioryou can specialize it for each specific kind of employee to reflect how the various types differ from the norm that isyou can code subclasses that customize just the bits of behavior that differ per employee typethe oopthe big picture |
1,353 | exampleif engineers have unique salary computation rule (perhaps it' not hours times rate)you can replace just that one method in subclassclass engineer(employee)def computesalary(self)specialized subclass something custom here because the computesalary version here appears lower in the class treeit will replace (overridethe general version in employee you then create instances of the kinds of employee classes that the real employees belong toto get the correct behaviorbob employee(sue employee(tom engineer(default behavior default behavior custom salary calculator notice that you can make instances of any class in treenot just the ones at the bottom --the class you make an instance from determines the level at which the attribute search will beginand thus which versions of the methods it will employ ultimatelythese three instance objects might wind up embedded in larger container object--for instancea listor an instance of another class--that represents department or company using the composition idea mentioned at the start of this when you later ask for these employeessalariesthey will be computed according to the classes from which the objects were madedue to the principles of the inheritance searchcompany [bobsuetomfor emp in companyprint(emp computesalary() composite object run this object' versiondefault or custom this is yet another instance of the idea of polymorphism introduced in and expanded in recall that polymorphism means that the meaning of an operation depends on the object being operated on that iscode shouldn' care about what an object isonly about what it does herethe method computesalary is located by inheritance search in each object before it is called the net effect is that we automatically run the correct version for the object being processed trace the code to see why in other applicationspolymorphism might also be used to hide ( encapsulateinterface differences for examplea program that processes data streams might be coded to expect objects with input and output methodswithout caring what those methods actually dodef processor(readerconverterwriter)while truedata reader read( the company list in this example could be database if stored in file with python object picklingintroduced in to make the employees persistent python also comes with module named shelvewhich allows the pickled representation of class instances to be stored in an access-by-key filesystemwe'll deploy it in oop from , feet |
1,354 | data converter(datawriter write(databy passing in instances of subclasses that specialize the required read and write method interfaces for various data sourceswe can reuse the processor function for any data source we need to useboth now and in the futureclass readerdef read(self)default behavior and tools def other(self)class filereader(reader)def read(self)read from local file class socketreader(reader)def read(self)read from network socket processor(filereader)converterfilewriter)processor(socketreader)convertertapewriter)processor(ftpreader)converterxmlwriter)moreoverbecause the internal implementations of those read and write methods have been factored into single locationsthey can be changed without impacting code such as this that uses them the processor function might even be class itself to allow the conversion logic of converter to be filled in by inheritanceand to allow readers and writers to be embedded by composition (we'll see how this works later in this part of the bookprogramming by customization once you get used to programming this way (by software customization)you'll find that when it' time to write new programmuch of your work may already be done --your task largely becomes one of mixing together existing superclasses that already implement the behavior required by your program for examplesomeone else might have written the employeereaderand writer classes in this section' examples for use in completely different programs if soyou get all of that person' code "for free in factin many application domainsyou can fetch or purchase collections of superclassesknown as frameworksthat implement common programming tasks as classesready to be mixed into your applications these frameworks might provide database interfacestesting protocolsgui toolkitsand so on with frameworksyou often simply code subclass that fills in an expected method or twothe framework classes higher in the tree do most of the work for you programming in such an oop world is just matter of combining and specializing already debugged code by writing subclasses of your own of courseit takes while to learn how to leverage classes to achieve such oop utopia in practiceobject-oriented work also entails substantial design work to fully realize the code reuse benefits of classes--to this endprogrammers have begun cataloging common oop structuresknown as design patternsto help with design issues the actual code you write to do oop in pythonthoughis so simple that it will not in itself oopthe big picture |
1,355 | summary we took an abstract look at classes and oop in this taking in the big picture before we dive into syntax details as we've seenoop is mostly about an argument named selfand search for attributes in trees of linked objects called inheritance objects at the bottom of the tree inherit attributes from objects higher up in the tree -- feature that enables us to program by customizing coderather than changing it or starting from scratch when used wellthis model of programming can cut development time radically the next will begin to fill in the coding details behind the picture painted here as we get deeper into python classesthoughkeep in mind that the oop model in python is very simpleas we've seen hereit' really just about looking up attributes in object trees and special function argument before we move onhere' quick quiz to review what we've covered here test your knowledgequiz what is the main point of oop in python where does an inheritance search look for an attribute what is the difference between class object and an instance object why is the first argument in class' method function special what is the __init__ method used for how do you create class instance how do you create class how do you specify class' superclassestest your knowledgeanswers oop is about code reuse--you factor code to minimize redundancy and program by customizing what already exists instead of changing code in place or starting from scratch an inheritance search looks for an attribute first in the instance objectthen in the class the instance was created fromthen in all higher superclassesprogressing from the bottom to the top of the object treeand from left to right (by defaultthe search stops at the first place the attribute is found because the lowest version of name found along the way winsclass hierarchies naturally support customization by extension in new subclasses test your knowledgeanswers |
1,356 | as attributesthe main difference between them is that classes are kind of factory for creating multiple instances classes also support operator overloading methodswhich instances inheritand treat any functions nested in the class as methods for processing instances the first argument in class' method function is special because it always receives the instance object that is the implied subject of the method call it' usually called self by convention because method functions always have this implied subject and object context by defaultwe say they are "object-oriented( designed to process or change objects if the __init__ method is coded or inherited in classpython calls it automatically each time an instance of that class is created it' known as the constructor methodit is passed the new instance implicitlyas well as any arguments passed explicitly to the class name it' also the most commonly used operator overloading method if no __init__ method is presentinstances simply begin life as empty namespaces you create class instance by calling the class name as though it were functionany arguments passed into the class name show up as arguments two and beyond in the __init__ constructor method the new instance remembers the class it was created from for inheritance purposes you create class by running class statementlike function definitionsthese statements normally run when the enclosing module file is imported (more on this in the next you specify class' superclasses by listing them in parentheses in the class statementafter the new class' name the left-to-right order in which the classes are listed in the parentheses gives the left-to-right inheritance search order in the class tree oopthe big picture |
1,357 | class coding basics now that we've talked about oop in the abstractit' time to see how this translates to actual code this begins to fill in the syntax details behind the class model in python if you've never been exposed to oop in the pastclasses can seem somewhat complicated if taken in single dose to make class coding easier to absorbwe'll begin our detailed exploration of oop by taking first look at some basic classes in action in this we'll expand on the details introduced here in later of this part of the bookbut in their basic formpython classes are easy to understand in factclasses have just three primary distinctions at base levelthey are mostly just namespacesmuch like the modules we studied in part unlike modulesthoughclasses also have support for generating multiple objectsfor namespace inheritanceand for operator overloading let' begin our class statement tour by exploring each of these three distinctions in turn classes generate multiple instance objects to understand how the multiple objects idea worksyou have to first understand that there are two kinds of objects in python' oop modelclass objects and instance objects class objects provide default behavior and serve as factories for instance objects instance objects are the real objects your programs process--each is namespace in its own rightbut inherits ( has automatic access tonames in the class from which it was created class objects come from statementsand instances come from callseach time you call classyou get new instance of that class this object-generation concept is very different from most of the other program constructs we've seen so far in this book in effectclasses are essentially factories for generating multiple instances by contrastonly one copy of each module is ever imported into single program in factthis is why reload works as it doesupdating singleinstance shared object in place with classeseach instance can have its ownindependent datasupporting multiple versions of the object that the class models |
1,358 | functions of but this is natural part of the class modeland state in classes is explicit attributes instead of implicit scope references moreoverthis is just part of what classes do--they also support customization by inheritanceoperator overloadingand multiple behaviors via methods generally speakingclasses are more complete programming toolthough oop and function programming are not mutually exclusive paradigms we may combine them by using functional tools in methodsby coding methods that are themselves generatorsby writing user-defined iterators (as we'll see in )and so on the following is quick summary of the bare essentials of python oop in terms of its two object types as you'll seepython classes are in some ways similar to both defs and modulesbut they may be quite different from what you're used to in other languages class objects provide default behavior when we run class statementwe get class object here' rundown of the main properties of python classesthe class statement creates class object and assigns it name just like the function def statementthe python class statement is an executable statement when reached and runit generates new class object and assigns it to the name in the class header alsolike defsclass statements typically run when the files they are coded in are first imported assignments inside class statements make class attributes just like in module filestop-level assignments within class statement (not nested in defgenerate attributes in class object technicallythe class statement defines local scope that morphs into the attribute namespace of the class objectjust like module' global scope after running class statementclass attributes are accessed by name qualificationobject name class attributes provide object state and behavior attributes of class object record state information and behavior to be shared by all instances created from the classfunction def statements nested inside class generate methodswhich process instances instance objects are concrete items when we call class objectwe get an instance object here' an overview of the key points behind class instancescalling class object like function makes new instance object each time class is calledit creates and returns new instance object instances represent concrete items in your program' domain class coding basics |
1,359 | instance objects created from classes are new namespacesthey start out empty but inherit attributes that live in the class objects from which they were generated assignments to attributes of self in methods make per-instance attributes inside class' method functionsthe first argument (called self by conventionreferences the instance object being processedassignments to attributes of self create or change data in the instancenot the class the end result is that classes define commonshared data and behaviorand generate instances instances reflect concrete application entitiesand record per-instance data that may vary per object first example let' turn to real example to show how these ideas work in practice to beginlet' define class named firstclass by running python class statement interactivelyclass firstclassdef setdata(selfvalue)self data value def display(self)print(self datadefine class object define class' methods self is the instance self dataper instance we're working interactively herebut typicallysuch statement would be run when the module file it is coded in is imported like functions created with defsthis class won' even exist until python reaches and runs this statement like all compound statementsthe class starts with header line that lists the class namefollowed by body of one or more nested and (usuallyindented statements herethe nested statements are defsthey define functions that implement the behavior the class means to export as we learned in part ivdef is really an assignment hereit assigns function objects to the names setdata and display in the class statement' scopeand so generates attributes attached to the class--firstclass setdata and firstclass display in factany name assigned at the top level of the class' nested block becomes an attribute of the class functions inside class are usually called methods they're coded with normal defsand they support everything we've learned about functions already (they can have defaultsreturn valuesyield items on requestand so onbut in method functionthe first argument automatically receives an implied instance object when called--the subject of the call we need to create couple of instances to see how this worksx firstclass( firstclass(make two instances each is new namespace by calling the class this way (notice the parentheses)we generate instance objectswhich are just namespaces that have access to their classesattributes properly speakclasses generate multiple instance objects |
1,360 | inheritance herethe "dataattribute is found in instancesbut "setdataand "displayare in the class above them ingat this pointwe have three objectstwo instances and class reallywe have three linked namespacesas sketched in figure - in oop termswe say that "is afirstclassas is --they both inherit names attached to the class the two instances start out empty but have links back to the class from which they were generated if we qualify an instance with the name of an attribute that lives in the class objectpython fetches the name from the class by inheritance search (unless it also lives in the instance) setdata("king arthur" setdata( call methodsself is runsfirstclass setdata( neither nor has setdata attribute of its ownso to find itpython follows the link from instance to class and that' about all there is to inheritance in pythonit happens at attribute qualification timeand it just involves looking up names in linked objects --hereby following the is- links in figure - in the setdata function inside firstclassthe value passed in is assigned to self data within methodself--the name given to the leftmost argument by convention--automatically refers to the instance being processed ( or )so the assignments store values in the instancesnamespacesnot the class'sthat' how the data names in figure - are created because classes can generate multiple instancesmethods must go through the self argument to get to the instance to be processed when we call the class' display method to print self datawe see that it' different in each instanceon the other handthe name display itself is the same in and yas it comes (is inheritedfrom the classx display(king arthur display( self data differs in each instance runsfirstclass display(ynotice that we stored different object types in the data member in each instance-- string and floating-point number as with everything else in pythonthere are no declarations for instance attributes (sometimes called members)they spring into existence the first time they are assigned valuesjust like simple variables in factif we were class coding basics |
1,361 | undefined name error--the attribute named data doesn' even exist in memory until it is assigned within the setdata method as another way to appreciate how dynamic this model isconsider that we can change instance attributes in the class itselfby assigning to self in methodsor outside the classby assigning to an explicit instance objectx data "new valuex display(new value can get/set attributes outside the class too although less commonwe could even generate an entirely new attribute in the instance' namespace by assigning to its name outside the class' method functionsx anothername "spamcan set new attributes here toothis would attach new attribute called anothernamewhich may or may not be used by any of the class' methodsto the instance object classes usually create all of the instance' attributes by assignment to the self argumentbut they don' have to-programs can fetchchangeor create attributes on any objects to which they have references it usually doesn' make sense to add data that the class cannot useand it' possible to prevent this with extra "privacycode based on attribute access operator overloadingas we'll discuss later in this book (see and stillfree attribute access translates to less syntaxand there are cases where it' even useful--for examplein coding data records of the sort we'll see later in this classes are customized by inheritance let' move on to the second major distinction of classes besides serving as factories for generating multiple instance objectsclasses also allow us to make changes by introducing new components (called subclasses)instead of changing existing components in place as we've seeninstance objects generated from class inherit the class' attributes python also allows classes to inherit from other classesopening the door to coding hierarchies of classes that specialize behavior--by redefining attributes in subclasses that appear lower in the hierarchywe override the more general definitions of those attributes higher in the tree in effectthe further down the hierarchy we gothe more specific the software becomes heretoothere is no parallel with moduleswhose attributes live in singleflat namespace that is not as amenable to customization in pythoninstances inherit from classesand classes inherit from superclasses here are the key ideas behind the machinery of attribute inheritancesuperclasses are listed in parentheses in class header to make class inherit attributes from another classjust list the other class in parentheses in the new classes are customized by inheritance |
1,362 | and the class that is inherited from is its superclass classes inherit attributes from their superclasses just as instances inherit the attribute names defined in their classesclasses inherit all of the attribute names defined in their superclassespython finds them automatically when they're accessedif they don' exist in the subclasses instances inherit attributes from all accessible classes each instance gets names from the class it' generated fromas well as all of that class' superclasses when looking for namepython checks the instancethen its classthen all superclasses each object attribute reference invokes newindependent search python performs an independent search of the class tree for each attribute fetch expression this includes references to instances and classes made outside class statements ( attr)as well as references to attributes of the self instance argument in class' method functions each self attr expression in method invokes new search for attr in self and above logic changes are made by subclassingnot by changing superclasses by redefining superclass names in subclasses lower in the hierarchy (class tree)subclasses replace and thus customize inherited behavior the net effect--and the main purpose of all this searching--is that classes support factoring and customization of code better than any other language tool we've seen so far on the one handthey allow us to minimize code redundancy (and so reduce maintenance costsby factoring operations into singleshared implementationon the otherthey allow us to program by customizing what already existsrather than changing it in place or starting from scratch strictly speakingpython' inheritance is bit richer than described herewhen we factor in new-style descriptors and metaclasses--advanced topics we'll study later--but we can safely restrict our scope to instances and their classesboth at this point in the book and in most python application code we'll define inheritance formally in second example to illustrate the role of inheritancethis next example builds on the previous one firstwe'll define new classsecondclassthat inherits all of firstclass' names and provides one of its ownclass secondclass(firstclass)inherits setdata def display(self)changes display print('current value "% "self data class coding basics |
1,363 | class tree heresecondclass redefines and so customizes the "displaymethod for its instances secondclass defines the display method to print with different format by defining an attribute with the same name as an attribute in firstclasssecondclass effectively replaces the display attribute in its superclass recall that inheritance searches proceed upward from instances to subclasses to superclassesstopping at the first appearance of the attribute name that it finds in this casesince the display name in secondclass will be found before the one in first classwe say that secondclass overrides firstclass' display sometimes we call this act of replacing attributes by redefining them lower in the tree overloading the net effect here is that secondclass specializes firstclass by changing the behavior of the display method on the other handsecondclass (and any instances created from itstill inherits the setdata method in firstclass verbatim let' make an instance to demonstratez secondclass( setdata( display(current value " finds setdata in firstclass finds overridden method in secondclass as beforewe make secondclass instance object by calling it the setdata call still runs the version in firstclassbut this time the display attribute comes from second class and prints custom message figure - sketches the namespaces involved nowhere' crucial thing to notice about oopthe specialization introduced in secondclass is completely external to firstclass that isit doesn' affect existing or future firstclass objectslike the from the prior examplex display(new value is still firstclass instance (old messagerather than changing firstclasswe customized it naturallythis is an artificial examplebut as rulebecause inheritance allows us to make changes like this in external components ( in subclasses)classes often support extension and reuse better than functions or modules can classes are customized by inheritance |
1,364 | before we move onremember that there' nothing magic about class name it' just variable assigned to an object when the class statement runsand the object can be referenced with any normal expression for instanceif our firstclass were coded in module file instead of being typed interactivelywe could import it and use its name normally in class header linefrom modulename import firstclass class secondclass(firstclass)def display(self)copy name into my scope use class name directly orequivalentlyimport modulename class secondclass(modulename firstclass)def display(self)access the whole module qualify to reference like everything elseclass names always live within moduleso they must follow all the rules we studied in part for examplemore than one class can be coded in single module file--like other statements in moduleclass statements are run during imports to define namesand these names become distinct module attributes more generallyeach module may arbitrarily mix any number of variablesfunctionsand classesand all names in module behave the same way the file food py demonstratesfood py var def func()class spamclass hamclass eggsfood var food func food spam food ham food eggs this holds true even if the module and class happen to have the same name for examplegiven the following fileperson pyclass personwe need to go through the module to fetch the class as usualimport person person person(import module class within module although this path may look redundantit' requiredperson person refers to the per son class inside the person module saying just person gets the modulenot the classunless the from statement is usedfrom person import person person(get class from module use class name as with any other variablewe can never see class in file without first importing and somehow fetching it from its enclosing file if this seems confusingdon' use the same name for module and class within it in factcommon convention in python dictates that class names should begin with an uppercase letterto help make them more distinct class coding basics |
1,365 | person person(lowercase for modules uppercase for classes alsokeep in mind that although classes and modules are both namespaces for attaching attributesthey correspond to very different source code structuresa module reflects an entire filebut class is statement within file we'll say more about such distinctions later in this part of the book classes can intercept python operators let' move on to the third and final major difference between classes and modulesoperator overloading in simple termsoperator overloading lets objects coded with classes intercept and respond to operations that work on built-in typesadditionslicingprintingqualificationand so on it' mostly just an automatic dispatch mechanism --expressions and other built-in operations route control to implementations in classes heretoothere is nothing similar in modulesmodules can implement function callsbut not the behavior of expressions although we could implement all class behavior as method functionsoperator overloading lets objects be more tightly integrated with python' object model moreoverbecause operator overloading makes our own objects act like built-insit tends to foster object interfaces that are more consistent and easier to learnand it allows class-based objects to be processed by code written to expect built-in type' interface here is quick rundown of the main ideas behind overloading operatorsmethods named with double underscores (__x__are special hooks in python classes we implement operator overloading by providing specially named methods to intercept operations the python language defines fixed and unchangeable mapping from each of these operations to specially named method such methods are called automatically when instances appear in built-in operations for instanceif an instance object inherits an __add__ methodthat method is called whenever the object appears in expression the method' return value becomes the result of the corresponding expression classes may override most built-in type operations there are dozens of special operator overloading method names for intercepting and implementing nearly every operation available for built-in types this includes expressionsbut also basic operations like printing and object creation there are no defaults for operator overloading methodsand none are required if class does not define or inherit an operator overloading methodit just means that the corresponding operation is not supported for the class' instances if there is no __add__for exampleexpressions raise exceptions new-style classes have some defaultsbut not for common operations in python xand so-called "new styleclasses in that we'll define latera root classes can intercept python operators |
1,366 | manyand not for most commonly used operations operators allow classes to integrate with python' object model by overloading type operationsthe user-defined objects we implement with classes can act just like built-insand so provide consistency as well as compatibility with expected interfaces operator overloading is an optional featureit' used primarily by people developing tools for other python programmersnot by application developers andcandidlyyou probably shouldn' use it just because it seems clever or "cool unless class needs to mimic built-in type interfacesit should usually stick to simpler named methods why would an employee database application support expressions like and +for examplenamed methods like giveraise and promote would usually make more sense because of thiswe won' go into details on every operator overloading method available in python in this book stillthere is one operator overloading method you are likely to see in almost every realistic python classthe __init__ methodwhich is known as the constructor method and is used to initialize objectsstate you should pay special attention to this methodbecause __init__along with the self argumentturns out to be key requirement to reading and understanding most oop code in python third example on to another example this timewe'll define subclass of the prior section' second class that implements three specially named attributes that python will call automatically__init__ is run when new instance object is createdself is the new thirdclass object __add__ is run when thirdclass instance appears in expression __str__ is run when an object is printed (technicallywhen it' converted to its print string by the str built-in function or its python internals equivalentour new subclass also defines normally named method called mulwhich changes the instance object in place here' the new subclassclass thirdclass(secondclass)def __init__(selfvalue)self data value def __add__(selfother)return thirdclass(self data otherdef __str__(self)return '[thirdclass% ]self data inherit from secondclass on "thirdclass(value)on "self otheron "print(self)""str() not to be confused with the __init__ py files in module packagesthe method here is class constructor function used to initialize the newly created instancenot module package see for more details class coding basics |
1,367 | self data *other in-place changenamed thirdclass('abc' display(current value "abcprint( [thirdclassabc__init__ called inherited method called 'xyzb display(current value "abcxyzprint( [thirdclassabcxyz__add__makes new instance has all thirdclass methods mul( print( [thirdclassabcabcabcmulchanges instance in place __str__returns display string __str__returns display string thirdclass "is asecondclassso its instances inherit the customized display method from secondclass of the preceding section this timethoughthirdclass creation calls pass an argument ( "abc"this argument is passed to the value argument in the __init__ constructor and assigned to self data there the net effect is that third class arranges to set the data attribute automatically at construction timeinstead of requiring setdata calls after the fact furtherthirdclass objects can now show up in expressions and print calls for +python passes the instance object on the left to the self argument in __add__ and the value on the right to otheras illustrated in figure - whatever __add__ returns becomes the result of the expression (more on its result in momentfor printpython passes the object being printed to self in __str__whatever string this method returns is taken to be the print string for the object with __str__ (or its more broadly relevant twin __repr__which we'll meet and use in the next we can use normal print to display objects of this classinstead of calling the special display method figure - in operator overloadingexpression operators and other built-in operations performed on class instances are mapped back to specially named methods in the class these special methods are optional and may be inherited as usual herea expression triggers the __add__ method classes can intercept python operators |
1,368 | specially named methods such as __init____add__and __str__ are inherited by subclasses and instancesjust like any other names assigned in class if they're not coded in classpython looks for such names in all its superclassesas usual operator overloading method names are also not built-in or reserved wordsthey are just attributes that python looks for when objects appear in various contexts python usually calls them automaticallybut they may occasionally be called by your code as well for examplethe __init__ method is often called manually to trigger initialization steps in superclassas we'll see in the next returning resultsor not some operator overloading methods like __str__ require resultsbut others are more flexible for examplenotice how the __add__ method makes and returns new instance object of its classby calling thirdclass with the result value--which in turn triggers __init__ to initialize the result this is common conventionand explains why in the listing has display methodit' thirdclass object toobecause that' what returns for this class' objects this essentially propagates the type by contrastmul changes the current instance object in placeby reassigning the self attribute we could overload the expression to do the latterbut this would be too different from the behavior of for built-in types such as numbers and stringsfor which it always makes new objects common practice dictates that overloaded operators should work the same way that built-in operator implementations do because operator overloading is really just an expression-to-method dispatch mechanismthoughyou can interpret operators any way you like in your own class objects why use operator overloadingas class designeryou can choose to use operator overloading or not your choice simply depends on how much you want your object to look and feel like built-in types as mentioned earlierif you omit an operator overloading method and do not inherit it from superclassthe corresponding operation will not be supported for your instancesif it' attemptedan exception will be raised (orin some cases like printinga standard default will be usedfranklymany operator overloading methods tend to be used only when you are implementing objects that are mathematical in naturea vector or matrix class may overload the addition operatorfor examplebut an employee class likely would not for simpler classesyou might not use overloading at alland would rely instead on explicit method calls to implement your objectsbehavior on the other handyou might decide to use operator overloading if you need to pass user-defined object to function that was coded to expect the operators available on built-in type like list or dictionary implementing the same operator set in your class will ensure that your objects support the same expected object interface and so are compatible with the function although we won' cover every operator overloading class coding basics |
1,369 | in action in one overloading method we will use often here is the __init__ constructor methodused to initialize newly created instance objectsand present in almost every realistic class because it allows classes to fill out the attributes in their new instances immediatelythe constructor is useful for almost every kind of class you might code in facteven though instance attributes are not declared in pythonyou can usually find out which attributes an instance will have by inspecting its class' __init__ method of coursethere' nothing wrong with experimenting with interesting language toolsbut they don' always translate to production code with time and experienceyou'll find these programming patterns and guidelines to be natural and nearly automatic the world' simplest python class we've begun studying class statement syntax in detail in this but ' again like to remind you that the basic inheritance model that classes produce is very simple --all it really involves is searching for attributes in trees of linked objects in factwe can create class with nothing in it at all the following statement makes class with no attributes attachedan empty namespace objectclass recpass empty namespace object we need the no-operation pass placeholder statement (discussed in here because we don' have any methods to code after we make the class by running this statement interactivelywe can start attaching attributes to the class by assigning names to it completely outside of the original class statementrec name 'bobrec age just objects with attributes andafter we've created these attributes by assignmentwe can fetch them with the usual syntax when used this waya class is roughly similar to "structin cor "recordin pascal it' basically an object with field names attached to it (as we'll see aheaddoing similar with dictionary keys requires extra characters)print(rec namebob like struct or record notice that this works even though there are no instances of the class yetclasses are objects in their own righteven without instances in factthey are just self-contained namespacesas long as we have reference to classwe can set or change its attributes anytime we wish watch what happens when we do create two instancesthoughx rec( rec(instances inherit class names the world' simplest python class |
1,370 | remember the class from which they were madethoughthey will obtain the attributes we attached to the class by inheritancex namey name ('bob''bob'name is stored on the class only reallythese instances have no attributes of their ownthey simply fetch the name attribute from the class object where it is stored if we do assign an attribute to an instancethoughit creates (or changesthe attribute in that objectand no other--cruciallyattribute references kick off inheritance searchesbut attribute assignments affect only the objects in which the assignments are made herethis means that gets its own namebut still inherits the name attached to the class above itx name 'suerec namex namey name ('bob''sue''bob'but assignment changes only in factas we'll explore in more detail in the attributes of namespace object are usually implemented as dictionariesand class inheritance trees are (generally speakingjust dictionaries with links to other dictionaries if you know where to lookyou can see this explicitly for examplethe __dict__ attribute is the namespace dictionary for most class-based objects some classes may also (or insteaddefine attributes in __slots__an advanced and seldom-used feature that we'll note in but largely postpone until and normally__dict__ literally is an instance' attribute namespace to illustratethe following was run in python the order of names and set of __x__ internal names present can vary from release to releaseand we filter out builtins with generator expression as we've done beforebut the names we assigned are present in alllist(rec __dict__ keys()['age''__module__''__qualname__''__weakref__''name''__dict__''__doc__'list(name for name in rec __dict__ if not name startswith('__')['age''name'list( __dict__ keys()['name'list( __dict__ keys()list(not required in python [herethe class' namespace dictionary shows the name and age attributes we assigned to itx has its own nameand is still empty because of this modelan attribute can often be fetched by either dictionary indexing or attribute notationbut only if it' present on the object in question--attribute notation kicks off inheritance searchbut indexing looks in the single object only (as we'll see laterboth have valid roles) namex __dict__['name'('sue''sue' class coding basics attributes present here are dict keys |
1,371 | __dict__['age'keyerror'agebut attribute fetch checks classes too indexing dict does not do inheritance to facilitate inheritance search on attribute fetcheseach instance has link to its class that python creates for us--it' called __class__if you want to inspect itx __class__ instance to class link classes also have __bases__ attributewhich is tuple of references to their superclass objects--in this example just the implied object root class in python we'll explore later (you'll get an empty tuple in instead)rec __bases__ (,class to superclasses link(in these two attributes are how class trees are literally represented in memory by python internal details like these are not required knowledge--class trees are implied by the code you runand their search is normally automatic--but they can often help demystify the model the main point to take away from this look under the hood is that python' class model is extremely dynamic classes and instances are just namespace objectswith attributes created on the fly by assignment those assignments usually happen within the class statements you codebut they can occur anywhere you have reference to one of the objects in the tree even methodsnormally created by def nested in classcan be created completely independently of any class object the followingfor exampledefines simple function outside of any class that takes one argumentdef uppername(obj)return obj name upper(still needs self argument (objthere is nothing about class here yet--it' simple functionand it can be called as such at this pointprovided we pass in an object obj with name attributewhose value in turn has an upper method--our class instances happen to fit the expected interfaceand kick off string uppercase conversionuppername( 'suecall as simple function if we assign this simple function to an attribute of our classthoughit becomes methodcallable through any instanceas well as through the class name itself as long as we pass in an instance manually-- technique we'll leverage further in the next rec method uppername now it' class' methodx method('suerun method to process the world' simplest python class |
1,372 | 'bobsamebut pass to self rec method( 'suecan call through instance or class normallyclasses are filled out by class statementsand instance attributes are created by assignments to self attributes in method functions the point againthoughis that they don' have to beoop in python really is mostly about looking up attributes in linked namespace objects records revisitedclasses versus dictionaries although the simple classes of the prior section are meant to illustrate class model basicsthe techniques they employ can also be used for real work for example and showed how to use dictionariestuplesand lists to record properties of entities in our programsgenerically called records it turns out that classes can often serve better in this role--they package information like dictionariesbut can also bundle processing logic in the form of methods for referencehere is an example for tupleand dictionary-based records we used earlier in the book (using one of many dictionary coding techniques)rec ('bob' ['dev''mgr']print(rec[ ]bob rec {rec['name''bobrec['age' rec['jobs'['dev''mgr'print(rec['name']bob tuple-based record dictionary-based record or }dict( = )etc this code emulates tools like records in other languages as we just sawthoughthere are also multiple ways to do the same with classes perhaps the simplest is this--trading keys for attributesclass recpass rec name 'bobrec age rec jobs ['dev''mgr'class-based record in factthis is one of the reasons the self argument must always be explicit in python methods--because methods can be created as simple functions independent of classthey need to make the implied instance argument explicit they can be called as either functions or methodsand python can neither guess nor assume that simple function might eventually become class' method the main reason for the explicit self argumentthoughis to make the meanings of names more obviousnames not referenced through self are simple variables mapped to scopeswhile names referenced through self with attribute notation are obviously instance attributes class coding basics |
1,373 | print(rec namebob this code has substantially less syntax than the dictionary equivalent it uses an empty class statement to generate an empty namespace object once we make the empty classwe fill it out by assigning class attributes over timeas before this worksbut new class statement will be required for each distinct record we will need perhaps more typicallywe can instead generate instances of an empty class to represent each distinct entityclass recpass pers rec(pers name 'bobpers jobs ['dev''mgr'pers age pers rec(pers name 'suepers jobs ['dev''cto'pers namepers name ('bob''sue'instance-based records herewe make two records from the same class instances start out life emptyjust like classes we then fill in the records by assigning to attributes this timethoughthere are two separate objectsand hence two separate name attributes in factinstances of the same class don' even have to have the same set of attribute namesin this exampleone has unique age name instances really are distinct namespacesso each has distinct attribute dictionary although they are normally filled out consistently by class' methodsthey are more flexible than you might expect finallywe might instead code more full-blown class to implement the record and its processing--something that data-oriented dictionaries do not directly supportclass persondef __init__(selfnamejobsage=none)self name name self jobs jobs self age age def info(self)return (self nameself jobsrec person('bob'['dev''mgr'] rec person('sue'['dev''cto']rec jobsrec info((['dev''mgr']('sue'['dev''cto'])class data logic construction calls attributes methods this scheme also makes multiple instancesbut the class is not empty this timewe've added logic (methodsto initialize instances at construction time and collect attributes the world' simplest python class |
1,374 | by always setting the namejoband age attributeseven though the latter can be omitted when an object is made togetherthe class' methods and instance attributes create packagewhich combines both data and logic we could further extend this code by adding logic to compute salariesparse namesand so on ultimatelywe might link the class into larger hierarchy to inherit and customize an existing set of methods via the automatic attribute search of classesor perhaps even store instances of the class in file with python object pickling to make them persistent in factwe will--in the next we'll expand on this analogy between classes and records with more realistic running example that demonstrates class basics in action to be fair to other toolsin this formthe two class construction calls above more closely resemble dictionaries made all at oncebut still seem less cluttered and provide extra processing methods in factthe class' construction calls more closely resemble ' named tuples--which makes sensegiven that named tuples really are classes with extra logic to map attributes to tuple offsetsrec dict(name='bob'age= jobs=['dev''mgr']dictionaries rec {'name''bob''age' 'jobs'['dev''mgr']rec rec('bob' ['dev''mgr']named tuples in the endalthough types like dictionaries and tuples are flexibleclasses allow us to add behavior to objects in ways that built-in types and simple functions do not directly support although we can store functions in dictionariestoousing them to process implied instances is nowhere near as natural and structured as it is in classes to see this more clearlylet' move ahead to the next summary this introduced the basics of coding classes in python we studied the syntax of the class statementand we saw how to use it to build up class inheritance tree we also studied how python automatically fills in the first argument in method functionshow attributes are attached to objects in class tree by simple assignmentand how specially named operator overloading methods intercept and implement built-in operations for our instances ( expressions and printingnow that we've learned all about the mechanics of coding classes in pythonthe next turns to larger and more realistic example that ties together much of what we've learned about oop so farand introduces some new topics after thatwe'll continue our look at class codingtaking second pass over the model to fill in some of the details that were omitted here to keep things simple firstthoughlet' work through quiz to review the basics we've covered so far class coding basics |
1,375 | how are classes related to modules how are instances and classes created where and how are class attributes created where and how are instance attributes created what does self mean in python class how is operator overloading coded in python class when might you want to support operator overloading in your classes which operator overloading method is most commonly used what are two key concepts required to understand python oop codetest your knowledgeanswers classes are always nested inside modulethey are attributes of module object classes and modules are both namespacesbut classes correspond to statements (not entire filesand support the oop notions of multiple instancesinheritanceand operator overloading (modules do notin sensea module is like singleinstance classwithout inheritancewhich corresponds to an entire file of code classes are made by running class statementsinstances are created by calling class as though it were function class attributes are created by assigning attributes to class object they are normally generated by top-level assignments nested in class statement--each name assigned in the class statement block becomes an attribute of the class object (technicallythe class statement' local scope morphs into the class object' attribute namespacemuch like moduleclass attributes can also be createdthoughby assigning attributes to the class anywhere reference to the class object exists--even outside the class statement instance attributes are created by assigning attributes to an instance object they are normally created within class' method functions coded inside the class statementby assigning attributes to the self argument (which is always the implied instanceagainthoughthey may be created by assignment anywhere reference to the instance appearseven outside the class statement normallyall instance attributes are initialized in the __init__ constructor methodthat waylater method calls can assume the attributes already exist self is the name commonly given to the first (leftmostargument in class' method functionpython automatically fills it in with the instance object that is the implied subject of the method call this argument need not be called self (though this is very strong convention)its position is what is significant (exc+or java programmers might prefer to call it this because in those languages test your knowledgeanswers |
1,376 | explicit operator overloading is coded in python class with specially named methodsthey all begin and end with double underscores to make them unique these are not built-in or reserved namespython just runs them automatically when an instance appears in the corresponding operation python itself defines the mappings from operations to special method names operator overloading is useful to implement objects that resemble built-in types ( sequences or numeric objects such as matrixes)and to mimic the built-in type interface expected by piece of code mimicking built-in type interfaces enables you to pass in class instances that also have state information ( attributes that remember data between operation callsyou shouldn' use operator overloading when simple named method will sufficethough the __init__ constructor method is the most commonly usedalmost every class uses this method to set initial values for instance attributes and perform other startup tasks the special self argument in method functions and the __init__ constructor method are the two cornerstones of oop code in pythonif you get theseyou should be able to read the text of most oop python code--apart from theseit' largely just packages of functions the inheritance search matters tooof coursebut self represents the automatic object argumentand __init__ is widespread class coding basics |
1,377 | more realistic example we'll dig into more class syntax details in the next before we dothoughi' like to show you more realistic example of classes in action that' more practical than what we've seen so far in this we're going to build set of classes that do something more concrete--recording and processing information about people as you'll seewhat we call instances and classes in python programming can often serve the same roles as records and programs in more traditional terms specificallyin this we're going to code two classesperson-- class that creates and processes information about people manager-- customization of person that modifies inherited behavior along the waywe'll make instances of both classes and test out their functionality when we're donei'll show you nice example use case for classes--we'll store our instances in shelve object-oriented databaseto make them permanent that wayyou can use this code as template for fleshing out full-blown personal database written entirely in python besides actual utilitythoughour aim here is also educationalthis provides tutorial on object-oriented programming in python oftenpeople grasp the last class syntax on paperbut have trouble seeing how to get started when confronted with having to code new class from scratch toward this endwe'll take it one step at time hereto help you learn the basicswe'll build up the classes graduallyso you can see how their features come together in complete programs in the endour classes will still be relatively small in terms of codebut they will demonstrate all of the main ideas in python' oop model despite its syntax detailspython' class system really is largely just matter of searching for an attribute in tree of objectsalong with special first argument for functions |
1,378 | okso much for the design phase--let' move on to implementation our first task is to start coding the main classperson in your favorite text editoropen new file for the code we'll be writing it' fairly strong convention in python to begin module names with lowercase letter and class names with an uppercase letterlike the name of self arguments in methodsthis is not required by the languagebut it' so common that deviating might be confusing to people who later read your code to conformwe'll call our new module file person py and our class within it personlike thisfile person py (startclass personstart class all our work will be done in this file until later in this we can code any number of functions and classes in single module file in pythonand this one' person py name might not make much sense if we add unrelated components to it later for nowwe'll assume everything in it will be person-related it probably should be anyhow--as we've learnedmodules tend to work best when they have singlecohesive purpose coding constructors nowthe first thing we want to do with our person class is record basic information about people--to fill out record fieldsif you will of coursethese are known as instance object attributes in python-speakand they generally are created by assignment to self attributes in class' method functions the normal way to give instance attributes their first values is to assign them to self in the __init__ constructor methodwhich contains code run automatically by python each time an instance is created let' add one to our classadd record field initialization class persondef __init__(selfnamejobpay)self name name self job job self pay pay constructor takes three arguments fill out fields when created self is the new instance object this is very common coding patternwe pass in the data to be attached to an instance as arguments to the constructor method and assign them to self to retain them permanently in oo termsself is the newly created instance objectand namejoband pay become state information--descriptive data saved on an object for later use although other techniques (such as enclosing scope reference closurescan save detailstooinstance attributes make this very explicit and easy to understand notice that the argument names appear twice here this code might even seem bit redundant at firstbut it' not the job argumentfor exampleis local variable in the scope of the __init__ functionbut self job is an attribute of the instance that' the more realistic example |
1,379 | have the same name by assigning the job local to the self job attribute with self job=jobwe save the passed-in job on the instance for later use as usual in pythonwhere name is assignedor what object it is assigned todetermines what it means speaking of argumentsthere' really nothing magical about __init__apart from the fact that it' called automatically when an instance is made and has special first argument despite its weird nameit' normal function and supports all the features of functions we've already covered we canfor exampleprovide defaults for some of its argumentsso they need not be provided in cases where their values aren' available or useful to demonstratelet' make the job argument optional--it will default to nonemeaning the person being created is not (currentlyemployed if job defaults to nonewe'll probably want to default pay to toofor consistency (unless some of the people you know manage to get paid without having jobs!in factwe have to specify default for pay because according to python' syntax rules and any arguments in function' header after the first default must all have defaultstooadd defaults for constructor arguments class persondef __init__(selfnamejob=nonepay= )self name name self job job self pay pay normal function args what this code means is that we'll need to pass in name when making personsbut job and pay are now optionalthey'll default to none and if omitted the self argumentas usualis filled in by python automatically to refer to the instance object-assigning values to attributes of self attaches them to the new instance testing as you go this class doesn' do much yet--it essentially just fills out the fields of new record-but it' real working class at this point we could add more code to it for more featuresbut we won' do that yet as you've probably begun to appreciate alreadyprogramming in python is really matter of incremental prototyping--you write some codetest itwrite more codetest againand so on because python provides both an interactive session and nearly immediate turnaround after code changesit' more natural to test as you go than to write huge amount of code to test all at once before adding more featuresthenlet' test what we've got so far by making few instances of our class and displaying their attributes as created by the constructor we could do this interactivelybut as you've also probably surmised by nowinteractive testing has its limits--it gets tedious to have to reimport modules and retype test cases each time you start new testing session more commonlypython programmers use step making instances |
1,380 | code at the bottom of the file that contains the objects to be testedlike thisadd incremental self-test code class persondef __init__(selfnamejob=nonepay= )self name name self job job self pay pay bob person('bob smith'sue person('sue jones'job='dev'pay= print(bob namebob payprint(sue namesue paytest the class runs __init__ automatically fetch attached attributes sue' and bob' attrs differ notice here that the bob object accepts the defaults for job and paybut sue provides values explicitly also note how we use keyword arguments when making suewe could pass by position insteadbut the keywords may help remind us later what the data isand they allow us to pass the arguments in any left-to-right order we like againdespite its unusual name__init__ is normal functionsupporting everything you already know about functions--including both defaults and pass-by-name keyword arguments when this file runs as scriptthe test code at the bottom makes two instances of our class and prints two attributes of each (name and pay) :\codeperson py bob smith sue jones you can also type this file' test code at python' interactive prompt (assuming you import the person class there first)but coding canned tests inside the module file like this makes it much easier to rerun them in the future although this is fairly simple codeit' already demonstrating something important notice that bob' name is not sue'sand sue' pay is not bob' each is an independent record of information technicallybob and sue are both namespace objects--like all class instancesthey each have their own independent copy of the state information created by the class because each instance of class has its own set of self attributesclasses are natural for recording information for multiple objects this wayjust like built-in types such as lists and dictionariesclasses serve as sort of object factory other python program structuressuch as functions and moduleshave no such concept ' closure functions come close in terms of per-call statebut don' have the multiple methodsinheritanceand larger structure we get from classes using code two ways as isthe test code at the bottom of the file worksbut there' big catch--its top-level print statements run both when the file is run as script and when it is imported as more realistic example |
1,381 | somewhere else (and we will soon in this we'll see the output of its test code every time the file is imported that' not very good software citizenshipthoughclient programs probably don' care about our internal tests and won' want to see our output mixed in with their own although we could split the test code off into separate fileit' often more convenient to code tests in the same file as the items to be tested it would be better to arrange to run the test statements at the bottom only when the file is run for testingnot when the file is imported that' exactly what the module __name__ check is designed foras you learned in the preceding part of this book here' what this addition looks like--add the require test and indent your self-test codeallow this file to be imported as well as run/tested class persondef __init__(selfnamejob=nonepay= )self name name self job job self pay pay if __name__ ='__main__'when run for testing only self-test code bob person('bob smith'sue person('sue jones'job='dev'pay= print(bob namebob payprint(sue namesue paynowwe get exactly the behavior we're after--running the file as top-level script tests it because its __name__ is __main__but importing it as library of classes later does notc:\codeperson py bob smith sue jones :\codepython python ( :bd afb ebf sep : : import person when importedthe file now defines the classbut does not use it when run directlythis file creates two instances of our class as beforeand prints two attributes of eachagainbecause each instance is an independent namespace objectthe values of their attributes differ version portabilityprints all of this code works on both python and xbut ' running it under python xand few of its outputs use print function calls with multiple arguments as explained in this means that some of its outputs may vary slightly under python if you run under the code will work as isbut you'll notice step making instances |
1,382 | multiple items into tuple in onlyc:\codec:\python \python person py ('bob smith' ('sue jones' if this difference is the sort of detail that might keep you awake at nightssimply remove the parentheses to use print statementsor add an import of python ' print function at the top of your scriptas shown in ( ' add this everywhere herebut it' bit distracting)from __future__ import print_function you can also avoid the extra parentheses portably by using formatting to yield single object to print either of the following works in both and xthough the method form is newerprint('{ { }format(bob namebob pay)print('% % (bob namebob pay)format method format expression as also described in such formatting may be required in some casesbecause objects nested in tuple may print differently than those printed as top-level objects--the former prints with __repr__ and the latter with __str__ (operator overloading methods discussed further in this as well as to sidestep this issuethis edition codes displays with __repr__ (the fallback in all casesincluding nesting and the interactive promptinstead of __str__ (the default for printsso that all object appearances print the same in and xeven those in superfluous tuple parenthesesstep adding behavior methods everything looks good so far--at this pointour class is essentially record factoryit creates and fills out fields of records (attributes of instancesin more pythonic termseven as limited as it isthoughwe can still run some operations on its objects although classes add an extra layer of structurethey ultimately do most of their work by embedding and processing basic core data types like lists and strings in other wordsif you already know how to use python' simple core typesyou already know much of the python class storyclasses are really just minor structural extension for examplethe name field of our objects is simple stringso we can extract last names from our objects by splitting on spaces and indexing these are all core data type operationswhich work whether their subjects are embedded in class instances or notname 'bob smithname split(['bob''smith'name split()[- 'smithsimple stringoutside class extract last name or [ ]if always just two parts more realistic example |
1,383 | its state information in place with an assignment this task also involves basic operations that work on python' core objectsregardless of whether they are standalone or embedded in class structure ( ' formatting the result in the following to mask the fact that different pythons print different number of decimal digits)pay pay * print(' fpay simple variableoutside class give raise orpay pay if you like to type orpay pay (pay )if you _really_ doto apply these operations to the person objects created by our scriptsimply do to bob name and sue pay what we just did to name and pay the operations are the samebut the subjects are attached as attributes to objects created from our classprocess embedded built-in typesstringsmutability class persondef __init__(selfnamejob=nonepay= )self name name self job job self pay pay if __name__ ='__main__'bob person('bob smith'sue person('sue jones'job='dev'pay= print(bob namebob payprint(sue namesue payprint(bob name split()[- ]extract object' last name sue pay * give this object raise print(' fsue paywe've added the last three lines herewhen they're runwe extract bob' last name by using basic string and list operations on his name fieldand give sue pay raise by modifying her pay attribute in place with basic number operations in sensesue is also mutable object--her state changes in place just like list after an append call here' the new version' outputbob smith sue jones smith the preceding code works as plannedbut if you show it to veteran software developer he or she will probably tell you that its general approach is not great idea in practice hardcoding operations like these outside of the class can lead to maintenance problems in the future for examplewhat if you've hardcoded the last-name-extraction formula at many different places in your programif you ever need to change the way it works (to support new name structurefor instance)you'll need to hunt down and update every occurrence similarlyif the pay-raise code ever changes ( to require approval or dastep adding behavior methods |
1,384 | across many filessplit into individual stepsand so on in prototype like thisfrequent change is almost guaranteed coding methods what we really want to do here is employ software design concept known as encapsulation--wrapping up operation logic behind interfacessuch that each operation is coded only once in our program that wayif our needs change in the futurethere is just one copy to update moreoverwe're free to change the single copy' internals almost arbitrarilywithout breaking the code that uses it in python termswe want to code operations on objects in class' methodsinstead of littering them throughout our program in factthis is one of the things that classes are very good at--factoring code to remove redundancy and thus optimize maintainability as an added bonusturning operations into methods enables them to be applied to any instance of the classnot just those that they've been hardcoded to process this is all simpler in code than it may sound in theory the following achieves encapsulation by moving the two operations from code outside the class to methods inside the class while we're at itlet' change our self-test code at the bottom to use the new methods we're creatinginstead of hardcoding operationsadd methods to encapsulate operations for maintainability class persondef __init__(selfnamejob=nonepay= )self name name self job job self pay pay def lastname(self)return self name split()[- def giveraise(selfpercent)self pay int(self pay ( percent)behavior methods self is implied subject must change here only if __name__ ='__main__'bob person('bob smith'sue person('sue jones'job='dev'pay= print(bob namebob payprint(sue namesue payprint(bob lastname()sue lastname()use the new methods sue giveraise instead of hardcoding print(sue payas we've learnedmethods are simply normal functions that are attached to classes and designed to process instances of those classes the instance is the subject of the method call and is passed to the method' self argument automatically the transformation to the methods in this version is straightforward the new last name methodfor examplesimply does to self what the previous version hardcoded more realistic example |
1,385 | returns the resultbecause this operation is called function nowit computes value for its caller to use arbitrarilyeven if it is just to be printed similarlythe new giveraise method just does to self what we did to sue before when run nowour file' output is similar to before--we've mostly just refactored the code to allow for easier changes in the futurenot altered its behaviorbob smith sue jones smith jones few coding details are worth pointing out here firstnotice that sue' pay is now still an integer after pay raise--we convert the math result back to an integer by calling the int built-in within the method changing the value to either int or float is probably not significant concern for this demointeger and floating-point objects have the same interfaces and can be mixed within expressions stillwe may need to address truncation and rounding issues in real system--money probably is significant to personsas we learned in we might handle this by using the round( built-in to round and retain centsusing the decimal type to fix precisionor storing monetary values as full floating-point numbers and displaying them with or { fformatting string to show cents as we did earlier for nowwe'll simply truncate any cents with int for another ideaalso see the money function in the formats py module of you could import this tool to show pay with commascentsand currency signs secondnotice that we're also printing sue' last name this time--because the last-name logic has been encapsulated in methodwe get to use it on any instance of the class as we've seenpython tells method which instance to process by automatically passing it in to the first argumentusually called self specificallyin the first callbob lastname()bob is the implied subject passed to self in the second callsue lastname()sue goes to self instead trace through these calls to see how the instance winds up in self--it' key concept the net effect is that the method fetches the name of the implied subject each time the same happens for giveraise we couldfor examplegive bob raise by calling giveraise for both instances this waytoo unfortunately for bobthoughhis zero starting pay will prevent him from getting raise as the program is currently coded-nothing times anything is nothingsomething we may want to address in future release of our software finallynotice that the giveraise method assumes that percent is passed in as floatingpoint number between zero and one that may be too radical an assumption in the real world ( raise would probably be bug for most of us!)we'll let it pass for this prototypebut we might want to test or at least document this in future iteration of step adding behavior methods |
1,386 | code something called function decorators and explore python' assert statement-alternatives that can do the validity test for us automatically during development in for examplewe'll write tool that lets us validate with strange incantations like the following@rangetest(percent=( )use decorator to validate def giveraise(selfpercent)self pay int(self pay ( percent)step operator overloading at this pointwe have fairly full-featured class that generates and initializes instancesalong with two new bits of behavior for processing instances in the form of methods so farso good as it standsthoughtesting is still bit less convenient than it needs to be--to trace our objectswe have to manually fetch and print individual attributes ( bob namesue payit would be nice if displaying an instance all at once actually gave us some useful information unfortunatelythe default display format for an instance object isn' very good--it displays the object' class nameand its address in memory (which is essentially useless in pythonexcept as unique identifierto see thischange the last line in the script to print(sueso it displays the object as whole here' what you'll get--the output says that sue is an "objectin xand an "instancein as codedbob smith sue jones smith jones providing print displays fortunatelyit' easy to do better by employing operator overloading--coding methods in class that intercept and process built-in operations when run on the class' instances specificallywe can make use of what are probably the second most commonly used operator overloading methods in pythonafter __init__the __repr__ method we'll deploy hereand its __str__ twin introduced in the preceding these methods are run automatically every time an instance is converted to its print string because that' what printing an object doesthe net transitive effect is that printing an object displays whatever is returned by the object' __str__ or __repr__ methodif the object either defines one itself or inherits one from superclass doubleunderscored names are inherited just like any other technically__str__ is preferred by print and strand __repr__ is used as fallback for these roles and in all other contexts although the two can be used to implement more realistic example |
1,387 | single display in all cases--printsnested appearancesand interactive echoes this still allows clients to provide an alternative display with __str__but for limited contexts onlysince this is self-contained examplethis is moot point here the __init__ constructor method we've already coded isstrictly speakingoperator overloading too--it is run automatically at construction time to initialize newly created instance constructors are so commonthoughthat they almost seem like special case more focused methods like __repr__ allow us to tap into specific operations and provide specialized behavior when our objects are used in those contexts let' put this into code the following extends our class to give custom display that lists attributes when our class' instances are displayed as wholeinstead of relying on the less useful default displayadd __repr__ overload method for printing objects class persondef __init__(selfnamejob=nonepay= )self name name self job job self pay pay def lastname(self)return self name split()[- def giveraise(selfpercent)self pay int(self pay ( percent)def __repr__(self)return '[person% % ](self nameself payadded method string to print if __name__ ='__main__'bob person('bob smith'sue person('sue jones'job='dev'pay= print(bobprint(sueprint(bob lastname()sue lastname()sue giveraise print(suenotice that we're doing string formatting to build the display string in __repr__ hereat the bottomclasses use built-in type objects and operations like these to get their work done againeverything you've already learned about both built-in types and functions applies to class-based code classes largely just add an additional layer of structure that packages functions and data together and supports extensions we've also changed our self-test code to print objects directlyinstead of printing individual attributes when runthe output is more coherent and meaningful nowthe "]lines are returned by our new __repr__run automatically by print operations[personbob smith [personsue jones smith jones [personsue jones step operator overloading |
1,388 | an as-code low-level display of an object when presentand __str__ is reserved for more user-friendly informational displays like ours here sometimes classes provide both __str__ for user-friendly displays and __repr__ with extra details for developers to view because printing runs __str__ and the interactive prompt echoes results with __repr__this can provide both target audiences with an appropriate display since __repr__ applies to more display casesincluding nested appearancesand because we're not interested in displaying two different formatsthe all-inclusive __repr__ is sufficient for our class herethis also means that our custom display will be used in if we list both bob and sue in print call-- technically nested appearanceper the sidebar in "version portabilityprintson page step customizing behavior by subclassing at this pointour class captures much of the oop machinery in pythonit makes instancesprovides behavior in methodsand even does bit of operator overloading now to intercept print operations in __repr__ it effectively packages our data and logic together into singleself-contained software componentmaking it easy to locate code and straightforward to change it in the future by allowing us to encapsulate behaviorit also allows us to factor that code to avoid redundancy and its associated maintenance headaches the only major oop concept it does not yet capture is customization by inheritance in some sensewe're already doing inheritancebecause instances inherit methods from their classes to demonstrate the real power of oopthoughwe need to define superclass/subclass relationship that allows us to extend our software and replace bits of inherited behavior that' the main idea behind oopafter allby fostering coding model based upon customization of work already doneit can dramatically cut development time coding subclasses as next stepthenlet' put oop' methodology to use and customize our person class by extending our software hierarchy for the purpose of this tutorialwe'll define subclass of person called manager that replaces the inherited giveraise method with more specialized version our new class begins as followsclass manager(person)define subclass of person this code means that we're defining new class named managerwhich inherits from and may add customizations to the superclass person in plain termsa manager is almost like person (admittedlya very long journey for very small joke )but manager has custom way to give raises more realistic example |
1,389 | passed-in percentage as usualbut also gets an extra bonus that defaults to for instanceif manager' raise is specified as %it will really get (any relation to persons living or dead isof coursestrictly coincidental our new method begins as followsbecause this redefinition of giveraise will be closer in the class tree to man ager instances than the original version in personit effectively replacesand thereby customizesthe operation recall that according to the inheritance search rulesthe lowest version of the name wins: inherit person attrs redefine to customize class manager(person)def giveraise(selfpercentbonus )augmenting methodsthe bad way nowthere are two ways we might code this manager customizationa good way and bad way let' start with the bad waysince it might be bit easier to understand the bad way is to cut and paste the code of giveraise in person and modify it for managerlike thisclass manager(person)def giveraise(selfpercentbonus )self pay int(self pay ( percent bonus)badcut and paste this works as advertised--when we later call the giveraise method of manager instanceit will run this custom versionwhich tacks on the extra bonus so what' wrong with something that runs correctlythe problem here is very general oneanytime you copy code with cut and pasteyou essentially double your maintenance effort in the future think about itbecause we copied the original versionif we ever have to change the way raises are given (and we probably will)we'll have to change the code in two placesnot one although this is small and artificial exampleit' also representative of universal issue--anytime you're tempted to program by copying code this wayyou probably want to look for better approach augmenting methodsthe good way what we really want to do here is somehow augment the original giveraiseinstead of replacing it altogether the good way to do that in python is by calling to the original version directlywith augmented argumentslike thisclass manager(person)def giveraise(selfpercentbonus )person giveraise(selfpercent bonusgoodaugment original and no offense to any managers in the audienceof course once taught python class in new jerseyand nobody laughed at this jokeamong others the organizers later told me it was group of managers evaluating python step customizing behavior by subclassing |
1,390 | an instance (the usual waywhere python sends the instance to the self argument automaticallyor through the class (the less common schemewhere you must pass the instance manuallyin more symbolic termsrecall that normal method call of this forminstance method(args is automatically translated by python into this equivalent formclass method(instanceargs where the class containing the method to be run is determined by the inheritance search rule applied to the method' name you can code either form in your scriptbut there is slight asymmetry between the two--you must remember to pass along the instance manually if you call through the class directly the method always needs subject instance one way or anotherand python provides it automatically only for calls made through an instance for calls through the class nameyou need to send an instance to self yourselffor code inside method like giveraiseself already is the subject of the calland hence the instance to pass along calling through the class directly effectively subverts inheritance and kicks the call higher up the class tree to run specific version in our casewe can use this technique to invoke the default giveraise in personeven though it' been redefined at the man ager level in some sensewe must call through person this waybecause self giver aise(inside manager' giveraise code would loop--since self already is managerself giveraise(would resolve again to manager giveraiseand so on and so forth recursively until available memory is exhausted this "goodversion may seem like small difference in codebut it can make huge difference for future code maintenance--because the giveraise logic lives in just one place now (person' method)we have only one version to change in the future as needs evolve and reallythis form captures our intent more directly anyhow--we want to perform the standard giveraise operationbut simply tack on an extra bonus here' our entire module file with this step appliedadd customization of one behavior in subclass class persondef __init__(selfnamejob=nonepay= )self name name self job job self pay pay def lastname(self)return self name split()[- def giveraise(selfpercent)self pay int(self pay ( percent)def __repr__(self)return '[person% % ](self nameself payclass manager(person) more realistic example |
1,391 | person giveraise(selfpercent bonusif __name__ ='__main__'bob person('bob smith'sue person('sue jones'job='dev'pay= print(bobprint(sueprint(bob lastname()sue lastname()sue giveraise print(suetom manager('tom jones''mgr' tom giveraise print(tom lastname()print(tomredefine at this level call person' version make manager__init__ runs custom version runs inherited method runs inherited __repr__ to test our manager subclass customizationwe've also added self-test code that makes managercalls its methodsand prints it when we make managerwe pass in nameand an optional job and pay as before--because manager had no __init__ constructorit inherits that in person here' the new version' output[personbob smith [personsue jones smith jones [personsue jones jones [persontom jones everything looks good herebob and sue are as beforeand when tom the manager is given raisehe really gets (his pay goes from $ to $ )because the customized giveraise in manager is run for him only also notice how printing tom as whole at the end of the test code displays the nice format defined in person' __repr__manager objects get thislastnameand the __init__ constructor method' code "for freefrom personby inheritance what about superto extend inherited methodsthe examples in this simply call the original through the superclass nameperson giveraisethis is the traditional and simplest scheme in pythonand the one used in most of this book java programmers may especially be interested to know that python also has super built-in function that allows calling back to superclass' methods more generically-but it' cumbersome to use in xdiffers in form between and xrelies on unusual semantics in xworks unevenly with python' operator overloadingand does not always mesh well with traditionally coded multiple inheritancewhere single superclass call won' suffice in its defensethe super call has valid use case too--cooperative same-named method dispatch in multiple inheritance trees--but it relies on the "mroordering of classeswhich many find esoteric and artificialunrealistically assumes universal deployment to be used reliablydoes not fully support method replacement and varying argument step customizing behavior by subclassing |
1,392 | python code because of these downsidesthis book prefers to call superclasses by explicit name instead of superrecommends the same policy for newcomersand defers presenting super until it' usually best judged after you learn the simplerand generally more traditional and "pythonicways of achieving the same goalsespecially if you're new to oop topics like mros and cooperative multiple inheritance dispatch seem lot to ask of beginners--and others and to any java programmers in the audiencei suggest resisting the temptation to use python' super until you've had chance to study its subtle implications once you step up to multiple inheritanceit' not what you think it isand more than you probably expect the class it invokes may not be the superclass at alland can even vary per context or to paraphrase movie linepython' super is like box of chocolates--you never know what you're going to getpolymorphism in action to make this acquisition of inherited behavior even more strikingwe can add the following code at the end of our file temporarilyif __name__ ='__main__'print('--all three--'for obj in (bobsuetom)obj giveraise print(objprocess objects generically run this object' giveraise run the common __repr__ here' the resulting outputwith its new parts highlighted in bold[personbob smith [personsue jones smith jones [personsue jones jones [persontom jones --all three-[personbob smith [personsue jones [persontom jones in the added codeobject is either person or managerand python runs the appropriate giveraise automatically--our original version in person for bob and sueand our customized version in manager for tom trace the method calls yourself to see how python selects the right giveraise method for each object this is just python' notion of polymorphismwhich we met earlier in the bookat work again--what giveraise does depends on what you do it to hereit' made all the more obvious when it selects from code we've written ourselves in classes the practical effect in this code is that sue gets another but tom gets another %because more realistic example |
1,393 | is at the heart of python' flexibility passing any of our three objects to function that calls giveraise methodfor examplewould have the same effectthe appropriate version would be run automaticallydepending on which type of object was passed on the other handprinting runs the same __repr__ for all three objectsbecause it' coded just once in person manager both specializes and applies the code we originally wrote in person although this example is smallit' already leveraging oop' talent for code customization and reusewith classesthis almost seems automatic at times inheritcustomizeand extend in factclasses can be even more flexible than our example implies in generalclasses can inheritcustomizeor extend existing code in superclasses for examplealthough we're focused on customization herewe can also add unique methods to manager that are not present in personif managers require something completely different (python namesake reference intendedthe following snippet illustrates heregiveraise redefines superclass' method to customize itbut somethingelse defines something new to extendclass persondef lastname(self)def giveraise(self)def __repr__(self)class manager(person)def giveraise(self)def somethingelse(self)tom manager(tom lastname(tom giveraise(tom somethingelse(print(tominherit customize extend inherited verbatim customized version extension here inherited overload method extra methods like this code' somethingelse extend the existing software and are available on manager objects onlynot on persons for the purposes of this tutorialhoweverwe'll limit our scope to customizing some of person' behavior by redefining itnot adding to it oopthe big idea as isour code may be smallbut it' fairly functional and reallyit already illustrates the main point behind oop in generalin oopwe program by customizing what has already been donerather than copying or changing existing code this isn' always an obvious win to newcomers at first glanceespecially given the extra coding requirements of classes but overallthe programming style implied by classes can cut development time radically compared to other approaches step customizing behavior by subclassing |
1,394 | eraise operation without subclassingbut none of the other options yield code as optimal as oursalthough we could have simply coded manager from scratch as newindependent codewe would have had to reimplement all the behaviors in person that are the same for managers although we could have simply changed the existing person class in place for the requirements of manager' giveraisedoing so would probably break the places where we still need the original person behavior although we could have simply copied the person class in its entiretyrenamed the copy to managerand changed its giveraisedoing so would introduce code redundancy that would double our work in the future--changes made to person in the future would not be picked up automaticallybut would have to be manually propagated to manager' code as usualthe cut-and-paste approach may seem quick nowbut it doubles your work in the future the customizable hierarchies we can build with classes provide much better solution for software that will evolve over time no other tools in python support this development mode because we can tailor and extend our prior work by coding new subclasseswe can leverage what we've already donerather than starting from scratch each timebreaking what already worksor introducing multiple copies of code that may all have to be updated in the future when done rightoop is powerful programmer' ally step customizing constructorstoo our code works as it isbut if you study the current version closelyyou may be struck by something bit odd--it seems pointless to have to provide mgr job name for manager objects when we create themthis is already implied by the class itself it would be better if we could somehow fill in this value automatically when manager is made the trick we need to improve on this turns out to be the same as the one we employed in the prior sectionwe want to customize the constructor logic for managers in such way as to provide job name automatically in terms of codewe want to redefine an __init__ method in manager that provides the mgr string for us and as in giveraise customizationwe also want to run the original __init__ in person by calling through the class nameso it still initializes our objectsstate information attributes the following extension to person py will do the job--we've coded the new manager constructor and changed the call that creates tom to not pass in the mgr job namefile person py add customization of constructor in subclass class persondef __init__(selfnamejob=nonepay= )self name name more realistic example |
1,395 | self pay pay def lastname(self)return self name split()[- def giveraise(selfpercent)self pay int(self pay ( percent)def __repr__(self)return '[person% % ](self nameself payclass manager(person)def __init__(selfnamepay)person __init__(selfname'mgr'paydef giveraise(selfpercentbonus )person giveraise(selfpercent bonusredefine constructor run original with 'mgrif __name__ ='__main__'bob person('bob smith'sue person('sue jones'job='dev'pay= print(bobprint(sueprint(bob lastname()sue lastname()sue giveraise print(suetom manager('tom jones' tom giveraise print(tom lastname()print(tomjob name not neededimplied/set by class againwe're using the same technique to augment the __init__ constructor here that we used for giveraise earlier--running the superclass version by calling through the class name directly and passing the self instance along explicitly although the constructor has strange namethe effect is identical because we need person' construction logic to run too (to initialize instance attributes)we really have to call it this wayotherwiseinstances would not have any attributes attached calling superclass constructors from redefinitions this way turns out to be very common coding pattern in python by itselfpython uses inheritance to look for and call only one __init__ method at construction time--the lowest one in the class tree if you need higher __init__ methods to be run at construction time (and you usually do)you must call them manuallyand usually through the superclass' name the upside to this is that you can be explicit about which argument to pass up to the superclass' constructor and can choose to not call it at allnot calling the superclass constructor allows you to replace its logic altogetherrather than augmenting it the output of this file' self-test code is the same as before--we haven' changed what it doeswe've simply restructured to get rid of some logical redundancy[personbob smith [personsue jones smith jones [personsue jones jones [persontom jones step customizing constructorstoo |
1,396 | in this complete formand despite their relatively small sizesour classes capture nearly all the important concepts in python' oop machineryinstance creation--filling out instance attributes behavior methods--encapsulating logic in class' methods operator overloading--providing behavior for built-in operations like printing customizing behavior--redefining methods in subclasses to specialize them customizing constructors--adding initialization logic to superclass steps most of these concepts are based upon just three simple ideasthe inheritance search for attributes in object treesthe special self argument in methodsand operator overloading' automatic dispatch to methods along the waywe've also made our code easy to change in the futureby harnessing the class' propensity for factoring code to reduce redundancy for examplewe wrapped up logic in methods and called back to superclass methods from extensions to avoid having multiple copies of the same code most of these steps were natural outgrowth of the structuring power of classes by and largethat' all there is to oop in python classes certainly can become larger than thisand there are some more advanced class conceptssuch as decorators and metaclasseswhich we will meet in later in terms of the basicsthoughour classes already do it all in factif you've grasped the workings of the classes we've writtenmost oop python code should now be within your reach other ways to combine classes having said thati should also tell you that although the basic mechanics of oop are simple in pythonsome of the art in larger programs lies in the way that classes are put together we're focusing on inheritance in this tutorial because that' the mechanism the python language providesbut programmers sometimes combine classes in other waystoo for examplea common coding pattern involves nesting objects inside each other to build up composites we'll explore this pattern in more detail in which is really more about design than about python as quick examplethoughwe could use this composition idea to code our manager extension by embedding personinstead of inheriting from it the following alternativecoded in file person-composite pydoes so by using the __get attr__ operator overloading method to intercept undefined attribute fetches and delegate them to the embedded object with the getattr built-in the getattr call was introduced in --it' the same as attribute fetch notation and thus per more realistic example |
1,397 | covered in full in but its basic usage is simple enough to leverage here by combining these toolsthe giveraise method here still achieves customizationby changing the argument passed along to the embedded object in effectmanager becomes controller layer that passes calls down to the embedded objectrather than up to superclass methodsfile person-composite py embedding-based manager alternative class personsame class managerdef __init__(selfnamepay)self person person(name'mgr'paydef giveraise(selfpercentbonus )self person giveraise(percent bonusdef __getattr__(selfattr)return getattr(self personattrdef __repr__(self)return str(self personembed person object intercept and delegate delegate all other attrs must overload again (in xif __name__ ='__main__'same the output of this version is the same as the priorso won' list it again the more important point here is that this manager alternative is representative of general coding pattern usually known as delegation-- composite-based structure that manages wrapped object and propagates method calls to it this pattern works in our examplebut it requires about twice as much code and is less well suited than inheritance to the kinds of direct customizations we meant to express (in factno reasonable python programmer would code this example this way in practiceexcept perhaps those writing general tutorials!manager isn' really person hereso we need extra code to manually dispatch method calls to the embedded objectoperator overloading methods like __repr__ must be redefined (in xat leastas noted in the upcoming sidebar "catching built-in attributes in xon page )and adding new manager behavior is less straightforward since state information is one level removed stillobject embeddingand design patterns based upon itcan be very good fit when embedded objects require more limited interaction with the container than direct customization implies controller layeror proxylike this alternative managerfor examplemight come in handy if we want to adapt class to an expected interface it does not supportor trace or validate calls to another object' methods (indeedwe will use nearly identical coding pattern when we study class decorators later in the bookmoreovera hypothetical department class like the following could aggregate other objects in order to treat them as set replace the self-test code at the bottom of the step customizing constructorstoo |
1,398 | book' examples doesfile person-department py aggregate embedded objects into composite class personsame class manager(person)same class departmentdef __init__(self*args)self members list(argsdef addmember(selfperson)self members append(persondef giveraises(selfpercent)for person in self membersperson giveraise(percentdef showall(self)for person in self membersprint(personif __name__ ='__main__'bob person('bob smith'sue person('sue jones'job='dev'pay= tom manager('tom jones' development department(bobsuedevelopment addmember(tomdevelopment giveraises development showall(embed objects in composite runs embedded objectsgiveraise runs embedded objects__repr__ when runthe department' showall method lists all of its contained objects after updating their state in true polymorphic fashion with giveraises[personbob smith [personsue jones [persontom jones interestinglythis code uses both inheritance and composition--department is composite that embeds and controls other objects to aggregatebut the embedded person and manager objects themselves use inheritance to customize as another examplea gui might similarly use inheritance to customize the behavior or appearance of labels and buttonsbut also composition to build up larger packages of embedded widgetssuch as input formscalculatorsand text editors the class structure to use depends on the objects you are trying to model--in factthe ability to model real-world entities this way is one of oop' strengths design issues like composition are explored in so we'll postpone further investigations for now but againin terms of the basic mechanics of oop in pythonour person and manager classes already tell the entire story now that you've mastered more realistic example |
1,399 | scripts is often natural next step--and the topic of the next section catching built-in attributes in an implementation notein python --and in when ' "new styleclasses are enabled--the alternative delegation-based manager class of the file person-composite py that we coded in this will not be able to intercept and delegate operator overloading method attributes like __repr__ without redefining them itself although we know that __repr__ is the only such name used in our specific examplethis is general issue for delegation-based classes recall that built-in operations like printing and addition implicitly invoke operator overloading methods such as __repr__ and __add__ in ' new-style classesbuilt-in operations like these do not route their implicit attribute fetches through generic attribute managersneither __getattr__ (run for undefined attributesnor its cousin __getattribute__ (run for all attributesis invoked this is why we have to redefine __repr__ redundantly in the alternative managerin order to ensure that printing is routed to the embedded person object in comment out this method to see this live--the manager instance prints with default in xbut still uses person' __repr__ in in factthe __repr__ in manager isn' required in at allas it' coded to use normal and default ( "classic"classesc:\codepy - person-composite py [personbob smith etc :\codepy - person-composite py [personbob smith etc [persontom jones technicallythis happens because built-in operations begin their implicit search for method names at the instance in ' default classic classesbut start at the class in ' mandated new-style classesskipping the instance entirely by contrastexplicit by-name attribute fetches are always routed to the instance first in both models in classic classesbuilt-ins route attributes this way too--printingfor exampleroutes __repr__ through __getattr__ this is why commenting out manager' __repr__ has no effect in xthe call is delegated to person new-style classes also inherit default for __repr__ from their automatic object superclass that would foil __getattr__but the new-style __getattribute__ doesn' intercept the name either this is changebut isn' show-stopper--delegation-based new-style classes can generally redefine operator overloading methods to delegate them to wrapped objectseither manually or via tools or superclasses this topic is too advanced to explore further in this tutorialthoughso don' sweat the details too much here watch for it to be revisited in and (the latter of which defines new-style classes more formally)to impact examples again in the attribute management coverage of step customizing constructorstoo |
Subsets and Splits