id
int64
0
25.6k
text
stringlengths
0
4.59k
1,400
workarounds)and to be special-case factor in nearly formal inheritance definition in in language like python that supports both attribute interception and operator overloadingthe impacts of this change can be as broad as this spread impliesstep using introspection tools let' make one final tweak before we throw our objects onto database as they areour classes are complete and demonstrate most of the basics of oop in python they still have two remaining issues we probably should iron outthoughbefore we go live with themfirstif you look at the display of the objects as they are right nowyou'll notice that when you print tom the managerthe display labels him as person that' not technically incorrectsince manager is kind of customized and specialized per son stillit would be more accurate to display an object with the most specific (that islowestclass possiblethe one an object is made from secondand perhaps more importantlythe current display format shows only the attributes we include in our __repr__and that might not account for future goals for examplewe can' yet verify that tom' job name has been set to mgr correctly by manager' constructorbecause the __repr__ we coded for person does not print this field worseif we ever expand or otherwise change the set of attributes assigned to our objects in __init__we'll have to remember to also update __repr__ for new names to be displayedor it will become out of sync over time the last point means thatyet againwe've made potential extra work for ourselves in the future by introducing redundancy in our code because any disparity in __repr__ will be reflected in the program' outputthis redundancy may be more obvious than the other forms we addressed earlierstillavoiding extra work in the future is generally good thing special class attributes we can address both issues with python' introspection tools--special attributes and functions that give us access to some of the internals of objectsimplementations these tools are somewhat advanced and generally used more by people writing tools for other programmers to use than by programmers developing applications even soa basic knowledge of some of these tools is useful because they allow us to write code that processes classes in generic ways in our codefor examplethere are two hooks that can help us outboth of which were introduced near the end of the preceding and used in earlier examplesthe built-in instance __class__ attribute provides link from an instance to the class from which it was created classes in turn have __name__just like modules more realistic example
1,401
and __bases__ sequence that provides access to superclasses we can use these here to print the name of the class from which an instance is made rather than one we've hardcoded the built-in object __dict__ attribute provides dictionary with one key/value pair for every attribute attached to namespace object (including modulesclassesand instancesbecause it is dictionarywe can fetch its keys listindex by keyiterate over its keysand so onto process all attributes generically we can use this here to print every attribute in any instancenot just those we hardcode in custom displaysmuch as we did in ' module tools we met the first of these categories in the prior but here' quick review at python' interactive prompt with the latest versions of our person py classes notice how we load person at the interactive prompt with from statement here--class names live in and are imported from modulesexactly like function names and other variablesfrom person import person bob person('bob smith'bob [personbob smith print(bob[personbob smith show bob' __repr__ (not __str__dittoprint =__str__ or __repr__ bob __class__ bob __class__ __name__ 'personshow bob' class and its name list(bob __dict__ keys()['pay''job''name'attributes are really dict keys use list to force list in for key in bob __dict__print(key'=>'bob __dict__[key]index manually pay = job =none name =bob smith for key in bob __dict__print(key'=>'getattr(bobkey)obj attrbut attr is var pay = job =none name =bob smith as noted briefly in the prior some attributes accessible from an instance might not be stored in the __dict__ dictionary if the instance' class defines __slots__an optional and relatively obscure feature of new-style classes (and hence all classes in python xthat stores attributes sequentially in the instancemay preclude an instance __dict__ altogetherand which we won' study in full until and since slots really belong to classes instead of instancesand since they are rarely step using introspection tools
1,402
__dict__ as we dothoughkeep in mind that some programs may need to catch exceptions for missing __dict__or use hasattr to test or getattr with default if its users might deploy slots as we'll see in the next section' code won' fail if used by class with slots (its lack of them is enough to guarantee __dict__but slots--and other "virtualattributes--won' be reported as instance data generic display tool we can put these interfaces to work in superclass that displays accurate class names and formats all attributes of an instance of any class open new file in your text editor to code the following--it' newindependent module named classtools py that implements just such class because its __repr__ display overload uses generic introspection toolsit will work on any instanceregardless of the instance' attributes set and because this is classit automatically becomes general formatting toolthanks to inheritanceit can be mixed into any class that wishes to use its display format as an added bonusif we ever want to change how instances are displayed we need only change this classas every class that inherits its __repr__ will automatically pick up the new format when it' next runfile classtools py (new"assorted class utilities and toolsclass attrdisplay""provides an inheritable display overload method that shows instances with their class names and name=value pair for each attribute stored on the instance itself (but not attrs inherited from its classescan be mixed into any classand will work on any instance ""def gatherattrs(self)attrs [for key in sorted(self __dict__)attrs append('% =% (keygetattr(selfkey))return 'join(attrsdef __repr__(self)return '[% % ](self __class__ __name__self gatherattrs()if __name__ ='__main__'class toptest(attrdisplay)count def __init__(self)self attr toptest count self attr toptest count+ toptest count + more realistic example
1,403
pass xy toptest()subtest(print(xprint(ymake two instances show all instance attrs show lowest class name notice the docstrings here--because this is general-purpose toolwe want to add some functional documentation for potential users to read as we saw in docstrings can be placed at the top of simple functions and modulesand also at the start of classes and any of their methodsthe help function and the pydoc tool extract and display these automatically we'll revisit docstrings for classes in when run directlythis module' self-test makes two instances and prints themthe __repr__ defined here shows the instance' classand all its attributes names and valuesin sorted attribute name order this output is the same in python and because each object' display is single constructed stringc:\codeclasstools py [toptestattr = attr = [subtestattr = attr = another design note herebecause this class uses __repr__ instead of __str__ its displays are used in all contextsbut its clients also won' have the option of providing an alternative low-level display--they can still add __str__but this applies to print and str only in more general toolusing __str__ instead limits display' scopebut leaves clients the option of adding __repr__ for secondary display at interactive prompts and nested appearances we'll follow this alternative policy when we code expanded versions of this class in for this demowe'll stick with the allinclusive __repr__ instance versus class attributes if you study the classtools module' self-test code long enoughyou'll notice that its class displays only instance attributesattached to the self object at the bottom of the inheritance treethat' what self' __dict__ contains as an intended consequencewe don' see attributes inherited by the instance from classes above it in the tree ( count in this file' self-test code-- class attribute used as an instance counterinherited class attributes are attached to the class onlynot copied down to instances if you ever do wish to include inherited attributes tooyou can climb the __class__ link to the instance' classuse the __dict__ there to fetch class attributesand then iterate through the class' __bases__ attribute to climb to even higher superclassesrepeating as necessary if you're fan of simple coderunning built-in dir call on the instance instead of using __dict__ and climbing would have much the same effectsince dir results include inherited names in the sorted results list in python from person import person bob person('bob smith' xkeys is listdir shows less step using introspection tools
1,404
['pay''job''name'instance attrs only dir(bobplus inherited attrs in classes ['__doc__''__init__''__module__''__repr__''giveraise''job''lastname''name''pay'if you're using python xyour output will varyand may be more than you bargained forhere' the result for the last two statements (keys list order can vary per run)list(bob __dict__ keys()['name''job''pay' keys is viewnot list dir(bob includes class type methods ['__class__''__delattr__''__dict__''__dir__''__doc__''__eq__''__format__''__ge__''__getattribute__''__gt__''__hash__''__init__'more omitted attrs '__setattr__''__sizeof__''__str__''__subclasshook__''__weakref__''giveraise''job''lastname''name''pay'the code and output here varies between python and xbecause ' dict keys is not listand ' dir returns extra class-type implementation attributes technicallydir returns more in because classes are all "new styleand inherit large set of operator overloading names from the class type in factas usual you'll probably want to filter out most of the __x__ names in the dir resultsince they are internal implementation details and not something you' normally want to displaylen(dir(bob) list(name for name in dir(bobif not name startswith('__')['giveraise''job''lastname''name''pay'in the interest of spacewe'll leave optional display of inherited class attributes with either tree climbs or dir as suggested experiments for now for more hints on this frontthoughwatch for the classtree py inheritance tree climber we will write in and the lister py attribute listers and climbers we'll code in name considerations in tool classes one last subtlety herebecause our attrdisplay class in the classtools module is general tool designed to be mixed into other arbitrary classeswe have to be aware of the potential for unintended name collisions with client classes as isi've assumed that client subclasses may want to use both its __repr__ and gatherattrsbut the latter of these may be more than subclass expects--if subclass innocently defines gather attrs name of its ownit will likely break our classbecause the lower version in the subclass will be used instead of ours to see this for yourselfadd gatherattrs to toptest in the file' self-test codeunless the new method is identicalor intentionally customizes the originalour tool class will more realistic example
1,405
the toptest instanceclass toptest(attrdisplay)def gatherattrs(self)return 'spamreplaces method in attrdisplaythis isn' necessarily bad--sometimes we want other methods to be available to subclasseseither for direct calls or for customization this way if we really meant to provide __repr__ onlythoughthis is less than ideal to minimize the chances of name collisions like thispython programmers often prefix methods not meant for external use with single underscore_gatherattrs in our case this isn' foolproof (what if another class defines _gatherattrstoo?)but it' usually sufficientand it' common python naming convention for methods internal to class better and less commonly used solution would be to use two underscores at the front of the method name only__gatherattrs for us python automatically expands such names to include the enclosing class' namewhich makes them truly unique when looked up by the inheritance search this is feature usually called pseudoprivate class attributeswhich we'll expand on in and deploy in an expanded version of this class there for nowwe'll make both our methods available our classesfinal form nowto use this generic tool in our classesall we need to do is import it from its modulemix it in by inheritance in our top-level classand get rid of the more specific __repr__ we coded before the new display overload method will be inherited by instances of personas well as managermanager gets __repr__ from personwhich now obtains it from the attrdisplay coded in another module here is the final version of our person py file with these changes appliedfile classtools py (newas listed earlier file person py (final""record and process information about people run this file directly to test its classes ""from classtools import attrdisplay class person(attrdisplay)""create and process person records ""def __init__(selfnamejob=nonepay= )self name name self job job self pay pay use generic display tool mix in repr at this level step using introspection tools
1,406
return self name split()[- assumes last is last def giveraise(selfpercent)self pay int(self pay ( percent)percent must be class manager(person)"" customized person with special requirements ""def __init__(selfnamepay)person __init__(selfname'mgr'payjob name is implied def giveraise(selfpercentbonus )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' tom giveraise print(tom lastname()print(tomas this is the final revisionwe've added few comments here to document our work --docstrings for functional descriptions and for smaller notesper best-practice conventionsas well as blank lines between methods for readability-- generally good style choice when classes or methods grow largewhich resisted earlier for these small classesin part to save space and keep the code more compact when we run this code nowwe see all the attributes of our objectsnot just the ones we hardcoded in the original __repr__ and our final issue is resolvedbecause attrdis play takes class names off the self instance directlyeach object is shown with the name of its closest (lowestclass--tom displays as manager nownot personand we can finally verify that his job name has been correctly filled in by the manager constructorc:\codeperson py [personjob=nonename=bob smithpay= [personjob=devname=sue jonespay= smith jones [personjob=devname=sue jonespay= jones [managerjob=mgrname=tom jonespay= this is the more useful display we were after from larger perspectivethoughour attribute display class has become general toolwhich we can mix into any class by inheritance to leverage the display format it defines furtherall its clients will auto more realistic example
1,407
powerful class tool conceptssuch as decorators and metaclassesalong with python' many introspection toolsthey allow us to write code that augments and manages classes in structured and maintainable ways step (final)storing objects in database at this pointour work is almost complete we now have two-module system that not only implements our original design goals for representing peoplebut also provides general attribute display tool we can use in other programs in the future by coding functions and classes in module fileswe've ensured that they naturally support reuse and by coding our software as classeswe've ensured that it naturally supports extension although our classes work as plannedthoughthe objects they create are not real database records that isif we kill pythonour instances will disappear--they're transient objects in memory and are not stored in more permanent medium like fileso they won' be available in future program runs it turns out that it' easy to make instance objects more permanentwith python feature called object persistence-making objects live on after the program that creates them exits as final step in this tutoriallet' make our objects permanent pickles and shelves object persistence is implemented by three standard library modulesavailable in every pythonpickle serializes arbitrary python objects to and from string of bytes dbm (named anydbm in python ximplements an access-by-key filesystem for storing strings shelve uses the other two modules to store python objects on file by key we met these modules very briefly in when we studied file basics they provide powerful data storage options although we can' do them complete justice in this tutorial or bookthey are simple enough that brief introduction is enough to get you started the pickle module the pickle module is sort of super-general object formatting and deformatting toolgiven nearly arbitrary python object in memoryit' clever enough to convert the object to string of byteswhich it can use later to reconstruct the original object in memory the pickle module can handle almost any object you can create--listsdicstep (final)storing objects in database
1,408
useful things to picklebecause they provide both data (attributesand behavior (methods)in factthe combination is roughly equivalent to "recordsand "programs because pickle is so generalit can replace extra code you might otherwise write to create and parse custom text file representations for your objects by storing an object' pickle string on fileyou effectively make it permanent and persistentsimply load and unpickle it later to re-create the original object the shelve module although it' easy to use pickle by itself to store objects in simple flat files and load them from there laterthe shelve module provides an extra layer of structure that allows you to store pickled objects by key shelve translates an object to its pickled string with pickle and stores that string under key in dbm filewhen later loadingshelve fetches the pickled string by key and re-creates the original object in memory with pickle this is all quite trickbut to your script shelve of pickled objects looks just like dictionary--you index by key to fetchassign to keys to storeand use dictionary tools such as leninand dict keys to get information shelves automatically map dictionary operations to objects stored in file in factto your script the only coding difference between shelve and normal dictionary is that you must open shelves initially and must close them after making changes the net effect is that shelve provides simple database for storing and fetching native python objects by keysand thus makes them persistent across program runs it does not support query tools such as sqland it lacks some advanced features found in enterprise-level databases (such as true transaction processing)but native python objects stored on shelve may be processed with the full power of the python language once they are fetched back by key storing objects on shelve database pickling and shelves are somewhat advanced topicsand we won' go into all their details hereyou can read more about them in the standard library manualsas well as application-focused books such as the programming python follow-up text this is all simpler in python than in englishthoughso let' jump into some code let' write new script that throws objects of our classes onto shelve in your text editoropen new file we'll call makedb py since this is new filewe'll need to import our classes in order to create few instances to store we used from to load class at the interactive prompt earlierbut reallyas with functions and other variablesthere are two ways to load class from file (class names are variables like any otherand not at all magic in this context) yeswe use "shelveas noun in pythonmuch to the chagrin of variety of editors 've worked with over the yearsboth electronic and human more realistic example
1,409
bob person personload class with import go through module name from person import person bob personload class with from use name directly we'll use from to load in our scriptjust because it' bit less to type to keep this simplecopy or retype in our new script the self-test lines from person py that make instances of our classesso we have something to store (this is simple demoso we won' worry about the test-code redundancy hereonce we have some instancesit' almost trivial to store them on shelve we simply import the shelve moduleopen new shelve with an external filenameassign the objects to keys in the shelveand close the shelve when we're done because we've made changesfile makedb pystore person objects on shelve database from person import personmanager load our classes bob person('bob smith're-create objects to be stored sue person('sue jones'job='dev'pay= tom manager('tom jones' import shelve db shelve open('persondb'for obj in (bobsuetom)db[obj nameobj db close(filename where objects are stored use object' name attr as key store object on shelve by key close after making changes notice how we assign objects to the shelve using their own names as keys this is just for conveniencein shelvethe key can be any stringincluding one we might create to be unique using tools such as process ids and timestamps (available in the os and time standard library modulesthe only rule is that the keys must be strings and should be uniquesince we can store just one object per keythough that object can be listdictionaryor other object containing many objects itself in factthe values we store under keys can be python objects of almost any sort--builtin types like stringslistsand dictionariesas well as user-defined class instancesand nested combinations of all of these and more for examplethe name and job attributes of our objects could be nested dictionaries and lists as in earlier incarnations in this book (though this would require bit of redesign to the current codethat' all there is to it--if this script has no output when runit means it probably workedwe're not printing anythingjust creating and storing objects in file-based database :\codemakedb py exploring shelves interactively at this pointthere are one or more real files in the current directory whose names all start with "persondbthe actual files created can vary per platformand just as in the built-in open functionthe filename in shelve open(is relative to the current working step (final)storing objects in database
1,410
objects don' delete these files--they are your databaseand are what you'll need to copy or transfer when you back up or move your storage you can look at the shelve' files if you want toeither from windows explorer or the python shellbut they are binary hash filesand most of their content makes little sense outside the context of the shelve module with python and no extra software installedour database is stored in three files (in xit' just one filepersondbbecause the bsddb extension module is preinstalled with python for shelvesin xbsddb is an optional third-party open source add-onfor examplepython' standard library glob module allows us to get directory listings in python code to verify the files hereand we can open the files in text or binary mode to explore strings and bytesimport glob glob glob('person*'['person-composite py''person-department py''person py''person pyc''persondb bak''persondb dat''persondb dir'print(open('persondb dir'read()'sue jones'( 'tom jones'( 'bob smith'( print(open('persondb dat','rb'read() '\ \ cperson\nperson\nq\ )\ \ } \ ( \ \ \ \ jobq\ nx\ \ more omitted this content isn' impossible to decipherbut it can vary on different platforms and doesn' exactly qualify as user-friendly database interfaceto verify our work betterwe can write another scriptor poke around our shelve at the interactive prompt because shelves are python objects containing python objectswe can process them with normal python syntax and development modes herethe interactive prompt effectively becomes database clientimport shelve db shelve open('persondb'reopen the shelve len(db list(db keys()['sue jones''tom jones''bob smith'three 'recordsstored bob db['bob smith'bob [personjob=nonename=bob smithpay= fetch bob by key runs __repr__ from attrdisplay bob lastname('smithruns lastname from person more realistic example keys is the index list(to make list in
1,411
print(key'=>'db[key]iteratefetchprint sue jones =[personjob=devname=sue jonespay= tom jones =[managerjob=mgrname=tom jonespay= bob smith =[personjob=nonename=bob smithpay= for key in sorted(db)print(key'=>'db[key]iterate by sorted keys bob smith =[personjob=nonename=bob smithpay= sue jones =[personjob=devname=sue jonespay= tom jones =[managerjob=mgrname=tom jonespay= notice that we don' have to import our person or manager classes here in order to load or use our stored objects for examplewe can call bob' lastname method freelyand get his custom print display format automaticallyeven though we don' have his person class in our scope here this works because when python pickles class instanceit records its self instance attributesalong with the name of the class it was created from and the module where the class lives when bob is later fetched from the shelve and unpickledpython will automatically reimport the class and link bob to it the upshot of this scheme is that class instances automatically acquire all their class behavior when they are loaded in the future we have to import our classes only to make new instancesnot to process existing ones although deliberate featurethis scheme has somewhat mixed consequencesthe downside is that classes and their module' files must be importable when an instance is later loaded more formallypickleable classes must be coded at the top level of module file accessible from directory listed on the sys path module search path (and shouldn' live in the topmost script filesmodule __main__ unless they're always in that module when usedbecause of this external module file requirementsome applications choose to pickle simpler objects such as dictionaries or listsespecially if they are to be transferred across the internet the upside is that changes in class' source code file are automatically picked up when instances of the class are loaded againthere is often no need to update stored objects themselvessince updating their class' code changes their behavior shelves also have well-known limitations (the database suggestions at the end of this mention few of thesefor simple object storagethoughshelves and pickles are remarkably easy-to-use tools updating objects on shelve now for one last scriptlet' write program that updates an instance (recordeach time it runsto prove the point that our objects really are persistent--that their current values are available every time python program runs the following fileupdatedb pyprints the database and gives raise to one of our stored objects each time if step (final)storing objects in database
1,412
"for free"--printing our objects automatically employs the general __repr__ overloading methodand we give raises by calling the giveraise method we wrote earlier this all "just worksfor objects based on oop' inheritance modeleven when they live in filefile updatedb pyupdate person object on database import shelve db shelve open('persondb'reopen shelve with same filename for key in sorted(db)print(key'\ =>'db[key]iterate to display database objects prints with custom format sue db['sue jones'sue giveraise db['sue jones'sue db close(index by key to fetch update in memory using class' method assign to key to update in shelve close after making changes because this script prints the database when it starts upwe have to run it at least twice to see our objects change here it is in actiondisplaying all records and increasing sue' pay each time it is run (it' pretty good script for sue something to schedule to run regularly as cron job perhaps?) :\codeupdatedb py bob smith =[personjob=nonename=bob smithpay= sue jones =[personjob=devname=sue jonespay= tom jones =[managerjob=mgrname=tom jonespay= :\codeupdatedb py bob smith =[personjob=nonename=bob smithpay= sue jones =[personjob=devname=sue jonespay= tom jones =[managerjob=mgrname=tom jonespay= :\codeupdatedb py bob smith =[personjob=nonename=bob smithpay= sue jones =[personjob=devname=sue jonespay= tom jones =[managerjob=mgrname=tom jonespay= :\codeupdatedb py bob smith =[personjob=nonename=bob smithpay= sue jones =[personjob=devname=sue jonespay= tom jones =[managerjob=mgrname=tom jonespay= againwhat we see here is product of the shelve and pickle tools we get from pythonand of the behavior we coded in our classes ourselves and once againwe can verify our script' work at the interactive prompt--the shelve' equivalent of database clientc:\codepython import shelve db shelve open('persondb'reopen database rec db['sue jones'fetch object by key rec [personjob=devname=sue jonespay= more realistic example
1,413
'jonesrec pay for another example of object persistence in this booksee the sidebar in titled "why you will careclasses and persistenceon page it stores somewhat larger composite object in flat file with pickle instead of shelvebut the effect is similar for more details and examples for both pickles and shelvessee also (file basicsand ( string tool changes)other booksand python' manuals future directions and that' wrap for this tutorial at this pointyou've seen all the basics of python' oop machinery in actionand you've learned ways to avoid redundancy and its associated maintenance issues in your code you've built full-featured classes that do real work as an added bonusyou've made them real database records by storing them in python shelveso their information lives on persistently there is much more we could explore hereof course for examplewe could extend our classes to make them more realisticadd new kinds of behavior to themand so on giving raisefor instanceshould in practice verify that pay increase rates are between zero and one--an extension we'll add when we meet decorators later in this book you might also mutate this example into personal contacts databaseby changing the state information stored on objectsas well as the classesmethods used to process it we'll leave this suggested exercise open to your imagination we could also expand our scope to use tools that either come with python or are freely available in the open source worldguis as iswe can only process our database with the interactive prompt' commandbased interfaceand scripts we could also work on expanding our object database' usability by adding desktop graphical user interface for browsing and updating its records guis can be built portably with either python' tkinter (tkinter in xstandard library supportor third-party toolkits such as wxpython and pyqt tkinter ships with pythonlets you build simple guis quicklyand is ideal for learning gui programming techniqueswxpython and pyqt tend to be more complex to use but often produce higher-grade guis in the end websites although guis are convenient and fastthe web is hard to beat in terms of accessibility we might also implement website for browsing and updating recordsinstead of or in addition to guis and the interactive prompt websites can be constructed with either basic cgi scripting tools that come with pythonor fullfeatured third-party web frameworks such as djangoturbogearspylonsfuture directions
1,414
in shelvepickle fileor other python-based mediumthe scripts that process it are simply run automatically on server in response to requests from web browsers and other clientsand they produce html to interact with usereither directly or by interfacing with framework apis rich internet application (riasystems such as silverlight and pyjamas also attempt to combine gui-like interactivity with web-based deployment web services although web clients can often parse information in the replies from websites ( technique colorfully known as "screen scraping")we might go further and provide more direct way to fetch records on the web via web services interface such as soap or xml-rpc calls--apis supported by either python itself or the third-party open source domainwhich generally map data to and from xml format for transmission to python scriptssuch apis return data more directly than text embedded in the html of reply page databases if our database becomes higher-volume or criticalwe might eventually move it from shelves to more full-featured storage mechanism such as the open source zodb object-oriented database system (oodb)or more traditional sql-based relational database system such as mysqloracleor postgresql python itself comes with the in-process sqlite database system built-inbut other open source options are freely available on the web zodbfor exampleis similar to python' shelve but addresses many of its limitationsbetter supporting larger databasesconcurrent updatestransaction processingand automatic write-through on inmemory changes (shelves can cache objects and flush to disk at close time with their writeback optionbut this has limitationssee other resourcessql-based systems like mysql offer enterprise-level tools for database storage and may be directly used from python script as we saw in mongodb offers an alternative approach that stores json documentswhich closely parallel python dictionaries and listsand are language neutralunlike pickle data orms if we do migrate to relational database system for storagewe don' have to sacrifice python' oop tools object-relational mappers (ormslike sqlobject and sqlalchemy can automatically map relational tables and rows to and from python classes and instancessuch that we can process the stored data using normal python class syntax this approach provides an alternative to oodbs like shelve and zodb and leverages the power of both relational databases and python' class model while hope this introduction whets your appetite for future explorationall of these topics are of course far beyond the scope of this tutorial and this book at large if you want to explore any of them on your ownsee the webpython' standard library manualsand application-focused books such as programming python in the latter more realistic example
1,415
website on top of the database to allow for browsing and updating instance records hope to see you there eventuallybut firstlet' return to class fundamentals and finish up the rest of the core python language story summary in this we explored all the fundamentals of python classes and oop in actionby building upon simple but real examplestep by step we added constructorsmethodsoperator overloadingcustomization with subclassesand introspectionbased toolsand we met other concepts such as compositiondelegationand polymorphism along the way in the endwe took objects created by our classes and made them persistent by storing them on shelve object database--an easy-to-use system for saving and retrieving native python objects by key while exploring class basicswe also encountered multiple ways to factor our code to reduce redundancy and minimize future maintenance costs finallywe briefly previewed ways to extend our code with application-programming tools such as guis and databasescovered in follow-up books in the next of this part of the bookwe'll return to our study of the details behind python' class model and investigate its application to some of the design concepts used to combine classes in larger programs before we move aheadthoughlet' work through this quiz to review what we covered here since we've already done lot of hands-on work in this we'll close with set of mostly theoryoriented questions designed to make you trace through some of the code and ponder some of the bigger ideas behind it test your knowledgequiz when we fetch manager object from the shelve and print itwhere does the display format logic come from when we fetch person object from shelve without importing its modulehow does the object know that it has giveraise method that we can call why is it so important to move processing into methodsinstead of hardcoding it outside the class why is it better to customize by subclassing rather than copying the original and modifying why is it better to call back to superclass method to run default actionsinstead of copying and modifying its code in subclass why is it better to use tools like __dict__ that allow objects to be processed generically than to write more custom code for each type of classtest your knowledgequiz
1,416
instead of inheritance what would you have to change if the objects coded in this used dictionary for names and list for jobsas in similar examples earlier in this book how might you modify the classes in this to implement personal contacts database in pythontest your knowledgeanswers in the final version of our classesmanager ultimately inherits its __repr__ printing method from attrdisplay in the separate classtools module and two levels up in the class tree manager doesn' have one itselfso the inheritance search climbs to its person superclassbecause there is no __repr__ there eitherthe search climbs higher and finds it in attrdisplay the class names listed in parentheses in class statement' header line provide the links to higher superclasses shelves (reallythe pickle module they useautomatically relink an instance to the class it was created from when that instance is later loaded back into memory python reimports the class from its module internallycreates an instance with its stored attributesand sets the instance' __class__ link to point to its original class this wayloaded instances automatically obtain all their original methods (like lastnamegiveraiseand __repr__)even if we have not imported the instance' class into our scope it' important to move processing into methods so that there is only one copy to change in the futureand so that the methods can be run on any instance this is python' notion of encapsulation--wrapping up logic behind interfacesto better support future code maintenance if you don' do soyou create code redundancy that can multiply your work effort as the code evolves in the future customizing with subclasses reduces development effort in oopwe code by customizing what has already been donerather than copying or changing existing code this is the real "big ideain oop--because we can easily extend our prior work by coding new subclasseswe can leverage what we've already done this is much better than either starting from scratch each timeor introducing multiple redundant copies of code that may all have to be updated in the future copying and modifying code doubles your potential work effort in the futureregardless of the context if subclass needs to perform default actions coded in superclass methodit' much better to call back to the original through the superclass' name than to copy its code this also holds true for superclass constructors againcopying code creates redundancywhich is major issue as code evolves generic tools can avoid hardcoded solutions that must be kept in sync with the rest of the class as it evolves over time generic __repr__ print methodfor exampleneed not be updated each time new attribute is added to instances in an more realistic example
1,417
appears and need be modified in only one place--changes in the generic version are picked up by all classes that inherit from the generic class againeliminating code redundancy cuts future development effortthat' one of the primary assets classes bring to the table inheritance is best at coding extensions based on direct customization (like our manager specialization of personcomposition is well suited to scenarios where multiple objects are aggregated into whole and directed by controller layer class inheritance passes calls up to reuseand composition passes down to delegate inheritance and composition are not mutually exclusiveoftenthe objects embedded in controller are themselves customizations based upon inheritance not much since this was really first-cut prototypebut the lastname method would need to be updated for the new name formatthe person constructor would have change the job default to an empty listand the manager class would probably need to pass along job list in its constructor instead of single string (self-test code would change as wellof coursethe good news is that these changes would need to be made in just one place--in our classeswhere such details are encapsulated the database scripts should work as isas shelves support arbitrarily nested data the classes in this could be used as boilerplate "templatecode to implement variety of types of databases essentiallyyou can repurpose them by modifying the constructors to record different attributes and providing whatever methods are appropriate for the target application for instanceyou might use attributes such as nameaddressbirthdayphoneemailand so on for contacts databaseand methods appropriate for this purpose method named sendmailfor examplemight use python' standard library smptlib module to send an email to one of the contacts automatically when called (see python' manuals or application-level books for more details on such toolsthe attrdisplay tool we wrote here could be used verbatim to print your objectsbecause it is intentionally generic most of the shelve database code here can be used to store your objectstoowith minor changes test your knowledgeanswers
1,418
class coding details if you haven' quite gotten all of python oop yetdon' worrynow that we've had first tourwe're going to dig bit deeper and study the concepts introduced earlier in further detail in this and the following we'll take another look at class mechanics herewe're going to study classesmethodsand inheritanceformalizing and expanding on some of the coding ideas introduced in because the class is our last namespace toolwe'll summarize python' namespace and scope concepts as well the next continues this in-depth second pass over class mechanics by covering one specific aspectoperator overloading besides presenting additional detailsthis and the next also give us an opportunity to explore some larger classes than those we have studied so far content noteif you've been reading linearlysome of this will be review and summary of topics introduced in the preceding case studyrevisited here by language topics with smaller and more self-contained examples for readers new to oop others may be tempted to skip some of this but be sure to see the namespace coverage hereas it explains some subtleties in python' class model the class statement although the python class statement may seem similar to tools in other oop languages on the surfaceon closer inspectionit is quite different from what some programmers are used to for exampleas in ++the class statement is python' main oop toolbut unlike in ++python' class is not declaration like defa class statement is an object builderand an implicit assignment--when runit generates class object and stores reference to it in the name used in the header also like defa class statement is true executable code--your class doesn' exist until python reaches and runs the class statement that defines it this typically occurs while importing the module it is coded inbut not before
1,419
class is compound statementwith body of statements typically indented appearing under the header in the headersuperclasses are listed in parentheses after the class nameseparated by commas listing more than one superclass leads to multiple inheritancewhich we'll discuss more formally in here is the statement' general formclass name(superclass)attr value def method(self)self attr value assign to name shared class data methods per-instance data within the class statementany assignments generate class attributesand specially named methods overload operatorsfor instancea function called __init__ is called at instance object construction timeif defined example as we've seenclasses are mostly just namespaces--that istools for defining names ( attributesthat export data and logic to clients class statement effectively defines namespace just as in module filethe statements nested in class statement body create its attributes when python executes class statement (not call to class)it runs all the statements in its bodyfrom top to bottom assignments that happen during this process create names in the class' local scopewhich become attributes in the associated class object because of thisclasses resemble both modules and functionslike functionsclass statements are local scopes where names created by nested assignments live like names in modulenames assigned in class statement become attributes in class object the main distinction for classes is that their namespaces are also the basis of inheritance in pythonreference attributes that are not found in class or instance object are fetched from other classes because class is compound statementany sort of statement can be nested inside its body--printassignmentsifdefand so on all the statements inside the class statement run when the class statement itself runs (not when the class is later called to make an instancetypicallyassignment statements inside the class statement make data attributesand nested defs make method attributes in generalthoughany type of name assignment at the top level of class statement creates same-named attribute of the resulting class object for exampleassignments of simple nonfunction objects to class attributes produce data attributesshared by all instances class coding details
1,420
spam shareddata( shareddata( spamy spam ( generates class data attribute make two instances they inherit and share 'spam( shareddata spamherebecause the name spam is assigned at the top level of class statementit is attached to the class and so will be shared by all instances we can change it by going through the class nameand we can refer to it through either instances or the class: shareddata spam spamy spamshareddata spam ( such class attributes can be used to manage information that spans all the instances- counter of the number of instances generatedfor example (we'll expand on this idea by example in nowwatch what happens if we assign the name spam through an instance instead of the classx spam spamy spamshareddata spam ( assignments to instance attributes create or change the names in the instancerather than in the shared class more generallyinheritance searches occur only on attribute referencesnot on assignmentassigning to an object' attribute always changes that objectand no other for exampley spam is looked up in the class by inheritancebut the assignment to spam attaches name to itself here' more comprehensive example of this behavior that stores the same name in two places suppose we run the following classclass mixednamesdata 'spamdef __init__(selfvalue)self data value def display(self)print(self datamixednames datadefine class assign class attr assign method name assign instance attr instance attrclass attr if you've used +you may recognize this as similar to the notion of ++' "staticdata members-members that are stored in the classindependent of instances in pythonit' nothing specialall class attributes are just names assigned in the class statementwhether they happen to reference functions ( ++' "methods"or something else ( ++' "members"in we'll also meet python static methods (akin to those in ++)which are just self-less functions that usually process class attributes unless the class has redefined the attribute assignment operation to do something unique with the __setattr__ operator overloading method (discussed in )or uses advanced attribute tools such as properties and descriptors (discussed in and much of this presents the normal casewhich suffices at this point in the bookbut as we'll see laterpython hooks allow programs to deviate from the norm often the class statement
1,421
contains an assignment statementbecause this assignment assigns the name data inside the classit lives in the class' local scope and becomes an attribute of the class object like all class attributesthis data is inherited and shared by all instances of the class that don' have data attributes of their own when we make instances of this classthe name data is attached to those instances by the assignment to self data in the constructor methodx mixednames( mixednames( display() display( spam spam make two instance objects each has its own data self data differsmixednames data is the same the net result is that data lives in two placesin the instance objects (created by the self data assignment in __init__)and in the class from which they inherit names (created by the data assignment in the classthe class' display method prints both versionsby first qualifying the self instanceand then the class by using these techniques to store attributes in different objectswe determine their scope of visibility when attached to classesnames are sharedin instancesnames record per-instance datanot shared behavior or data although inheritance searches look up names for uswe can always get to an attribute anywhere in tree by accessing the desired object directly in the preceding examplefor instancespecifying data or self data will return an instance namewhich normally hides the same name in the classhowevermixed names data grabs the class' version of the name explicitly the next section describes one of the most common roles for such coding patternsand explains more about the way we deployed it in the prior methods because you already know about functionsyou also know about methods in classes methods are just function objects created by def statements nested in class statement' body from an abstract perspectivemethods provide behavior for instance objects to inherit from programming perspectivemethods work in exactly the same way as simple functionswith one crucial exceptiona method' first argument always receives the instance object that is the implied subject of the method call in other wordspython automatically maps instance method calls to class' method functions as follows method calls made through an instancelike thisinstance method(args are automatically translated to class method function calls of this formclass method(instanceargs class coding details
1,422
search procedure in factboth call forms are valid in python besides the normal inheritance of method attribute namesthe special first argument is the only real magic behind method calls in class' methodthe first argument is usually called self by convention (technicallyonly its position is significantnot its namethis argument provides methods with hook back to the instance that is the subject of the call--because classes generate many instance objectsthey need to use this argument to manage data that varies per instance +programmers may recognize python' self argument as being similar to ++' this pointer in pythonthoughself is always explicit in your codemethods must always go through self to fetch or change attributes of the instance being processed by the current method call this explicit nature of self is by design--the presence of this name makes it obvious that you are using instance attribute names in your scriptnot names in the local or global scope method example to clarify these conceptslet' turn to an example suppose we define the following classclass nextclassdef printer(selftext)self message text print(self messagedefine class define method change instance access instance the name printer references function objectbecause it' assigned in the class statement' scopeit becomes class object attribute and is inherited by every instance made from the class normallybecause methods like printer are designed to process instanceswe call them through instancesx nextclass( printer('instance call'instance call message 'instance callmake instance call its method instance changed when we call the method by qualifying an instance like thisprinter is first located by inheritanceand then its self argument is automatically assigned the instance object ( )the text argument gets the string passed at the call ('instance call'notice that because python automatically passes the first argument to self for uswe only actually have to pass in one argument inside printerthe name self is used to access or set per-instance data because it refers back to the instance currently being processed as we've seenthoughmethods may be called in one of two ways--through an instanceor through the class itself for examplewe can also call printer by going through the class nameprovided we pass an instance to the self argument explicitlymethods
1,423
class call message 'class calldirect class call instance changed again calls routed through the instance and the class have the exact same effectas long as we pass the same instance object ourselves in the class form by defaultin factyou get an error message if you try to call method without any instancenextclass printer('bad call'typeerrorunbound method printer(must be called with nextclass instance calling superclass constructors methods are normally called through instances calls to methods through classthoughdo show up in variety of special roles one common scenario involves the constructor method the __init__ methodlike all attributesis looked up by inheritance this means that at construction timepython locates and calls just one __init__ if subclass constructors need to guarantee that superclass construction-time logic runstoothey generally must call the superclass' __init__ method explicitly through the classclass superdef __init__(selfx)default code class sub(super)def __init__(selfxy)super __init__(selfxcustom code run superclass __init__ do my init actions sub( this is one of the few contexts in which your code is likely to call an operator overloading method directly naturallyyou should call the superclass constructor this way only if you really want it to run--without the callthe subclass replaces it completely for more realistic illustration of this technique in actionsee the manager class example in the prior tutorial other method call possibilities this pattern of calling methods through class is the general basis of extending-instead of completely replacing--inherited method behavior it requires an explicit instance to be passed because all methods do by default technicallythis is because methods are instance methods in the absence of any special code on related noteyou can also code multiple __init__ methods within the same classbut only the last definition will be usedsee for more details on multiple method definitions class coding details
1,424
allow you to code methods that do not expect instance objects in their first arguments such methods can act like simple instanceless functionswith names that are local to the classes in which they are codedand may be used to manage class data related concept we'll meet in the same the class methodreceives class when called instead of an instance and can be used to manage per-class dataand is implied in metaclasses these are both advanced and usually optional extensionsthough normallyan instance must always be passed to method--whether automatically when it is called through an instanceor manually when you call through class per the sidebar "what about super?on page in python also has super built-in function that allows calling back to superclass' methods more genericallybut we'll defer its presentation until due to its downsides and complexities see the aforementioned sidebar for more detailsthis call has well-known tradeoffs in basic usageand an esoteric advanced use case that requires universal deployment to be most effective because of these issuesthis book prefers to call superclasses by explicit name instead of super as policyif you're new to pythoni recommend the same approach for nowespecially for your first pass over oop learn the simple way nowso you can compare it to others later inheritance of coursethe whole point of the namespace created by the class statement is to support name inheritance this section expands on some of the mechanisms and roles of attribute inheritance in python as we've seenin pythoninheritance happens when an object is qualifiedand it involves searching an attribute definition tree--one or more namespaces every time you use an expression of the form object attr where object is an instance or class objectpython searches the namespace tree from bottom to topbeginning with objectlooking for the first attr it can find this includes references to self attributes in your methods because lower definitions in the tree override higher onesinheritance forms the basis of specialization attribute tree construction figure - summarizes the way namespace trees are constructed and populated with names generallyinstance attributes are generated by assignments to self attributes in methods class attributes are created by statements (assignmentsin class statements inheritance
1,425
header the net result is tree of attribute namespaces that leads from an instanceto the class it was generated fromto all the superclasses listed in the class header python searches upward in this treefrom instances to superclasseseach time you use qualification to fetch an attribute name from an instance object figure - program code creates tree of objects in memory to be searched by attribute inheritance calling class creates new instance that remembers its classrunning class statement creates new classand superclasses are listed in parentheses in the class statement header each attribute reference triggers new bottom-up tree search--even references to self attributes within class' methods specializing inherited methods the tree-searching model of inheritance just described turns out to be great way to specialize systems because inheritance finds names in subclasses before it checks superclassessubclasses can replace default behavior by redefining their superclasses two fine points herefirstthis description isn' completebecause we can also create instance and class attributes by assigning them to objects outside class statements--but that' much less common and sometimes more error-prone approach (changes aren' isolated to class statementsin pythonall attributes are always accessible by default we'll talk more about attribute name privacy in when we study __setattr__in when we meet __x namesand again in where we'll implement it with class decorator secondas also noted in the full inheritance story grows more convoluted when advanced topics such as metaclasses and descriptors are added to the mix--and we're deferring formal definition until for this reason in common usagethoughit' simply way to redefineand hence customizebehavior coded in classes class coding details
1,426
extend by adding new external subclasses rather than changing existing logic in place the idea of redefining inherited names leads to variety of specialization techniques for instancesubclasses may replace inherited attributes completelyprovide attributes that superclass expects to findand extend superclass methods by calling back to the superclass from an overridden method we've already seen some of these patterns in actionhere' self-contained example of extension at workclass superdef method(self)print('in super method'class sub(super)def method(self)print('starting sub method'super method(selfprint('ending sub method'override method add actions here run default action direct superclass method calls are the crux of the matter here the sub class replaces super' method function with its own specialized versionbut within the replacementsub calls back to the version exported by super to carry out the default behavior in other wordssub method just extends super method' behaviorrather than replacing it completelyx super( method(in super method make super instance runs super method sub( method(starting sub method in super method ending sub method make sub instance runs sub methodcalls super method this extension coding pattern is also commonly used with constructorssee the section "methodson page for an example class interface techniques extension is only one way to interface with superclass the file shown in this sectionspecialize pydefines multiple classes that illustrate variety of common techniquessuper defines method function and delegate that expects an action in subclass inheritor doesn' provide any new namesso it gets everything defined in super replacer overrides super' method with version of its own inheritance
1,427
customizes super' method by overriding and calling back to run the default provider implements the action method expected by super' delegate method study each of these subclasses to get feel for the various ways they customize their common superclass here' the fileclass superdef method(self)print('in super method'def delegate(self)self action(default behavior expected to be defined class inheritor(super)pass inherit method verbatim class replacer(super)def method(self)print('in replacer method'replace method completely class extender(super)extend method behavior def method(self)print('starting extender method'super method(selfprint('ending extender method'class provider(super)def action(self)print('in provider action'fill in required method if __name__ ='__main__'for klass in (inheritorreplacerextender)print('\nklass __name__ 'klass(method(print('\nprovider ' provider( delegate( few things are worth pointing out here firstnotice how the self-test code at the end of this example creates instances of three different classes in for loop because classes are objectsyou can store them in tuple and create instances generically with no extra syntax (more on this idea laterclasses also have the special __name__ attributelike modulesit' preset to string containing the name in the class header here' what happens when we run the filepython specialize py inheritor in super method replacer in replacer method class coding details
1,428
starting extender method in super method ending extender method provider in provider action abstract superclasses of the prior example' classesprovider may be the most crucial to understand when we call the delegate method through provider instancetwo independent inheritance searches occur on the initial delegate callpython finds the delegate method in super by searching the provider instance and above the instance is passed into the method' self argument as usual inside the super delegate methodself action invokes newindependent inheritance search of self and above because self references provider instancethe action method is located in the provider subclass this "filling in the blankssort of coding structure is typical of oop frameworks in more realistic contextthe method filled in this way might handle an event in guiprovide data to be rendered as part of web pageprocess tag' text in an xml fileand so on--your subclass provides specific actionsbut the framework handles the rest of the overall job at least in terms of the delegate methodthe superclass in this example is what is sometimes called an abstract superclass-- class that expects parts of its behavior to be provided by its subclasses if an expected method is not defined in subclasspython raises an undefined name exception when the inheritance search fails class coders sometimes make such subclass requirements more obvious with assert statementsor by raising the built-in notimplementederror exception with raise statements we'll study statements that may trigger exceptions in depth in the next part of this bookas quick previewhere' the assert scheme in actionclass superdef delegate(self)self action(def action(self)assert false'action must be defined!if this version is called super( delegate(assertionerroraction must be definedwe'll meet assert in and in shortif its first expression evaluates to falseit raises an exception with the provided error message herethe expression is inheritance
1,429
tederror exception directly in such method stubs to signal the mistakeclass superdef delegate(self)self action(def action(self)raise notimplementederror('action must be defined!' super( delegate(notimplementederroraction must be definedfor instances of subclasseswe still get the exception unless the subclass provides the expected method to replace the default in the superclassclass sub(super)pass sub( delegate(notimplementederroraction must be definedclass sub(super)def action(self)print('spam' sub( delegate(spam for somewhat more realistic example of this section' concepts in actionsee the "zoo animal hierarchyexercise (exercise at the end of and its solution in "part viclasses and oopin appendix such taxonomies are traditional way to introduce oopbut they're bit removed from most developersjob descriptions (with apologies to any readers who happen to work at the zoo!abstract superclasses in python and +preview as of python and the prior section' abstract superclasses ( "abstract base classes")which require methods to be filled in by subclassesmay also be implemented with special class syntax the way we code this varies slightly depending on the version in python xwe use keyword argument in class headeralong with special decorator syntaxboth of which we'll study in detail later in this bookfrom abc import abcmetaabstractmethod class super(metaclass=abcmeta)@abstractmethod def method(self)pass but in python and we use class attribute instead class coding details
1,430
__metaclass__ abcmeta @abstractmethod def method(self)pass either waythe effect is the same--we can' make an instance unless the method is defined lower in the class tree in xfor examplehere is the special syntax equivalent of the prior section' examplefrom abc import abcmetaabstractmethod class super(metaclass=abcmeta)def delegate(self)self action(@abstractmethod def action(self)pass super(typeerrorcan' instantiate abstract class super with abstract methods action class sub(super)pass sub(typeerrorcan' instantiate abstract class sub with abstract methods action class sub(super)def action(self)print('spam' sub( delegate(spam coded this waya class with an abstract method cannot be instantiated (that iswe cannot create an instance by calling itunless all of its abstract methods have been defined in subclasses although this requires more code and extra knowledgethe potential advantage of this approach is that errors for missing methods are issued when we attempt to make an instance of the classnot later when we try to call missing method this feature may also be used to define an expected interfaceautomatically verified in client classes unfortunatelythis scheme also relies on two advanced language tools we have not met yet--function decoratorsintroduced in and covered in depth in as well as metaclass declarationsmentioned in and covered in --so we will finesse other facets of this option here see python' standard manuals for more on thisas well as precoded abstract superclasses python provides inheritance
1,431
now that we've examined class and instance objectsthe python namespace story is complete for referencei'll quickly summarize all the rules used to resolve names here the first things you need to remember are that qualified and unqualified names are treated differentlyand that some scopes serve to initialize object namespacesunqualified names ( xdeal with scopes qualified attribute names ( object xuse object namespaces some scopes initialize object namespaces (for modules and classesthese concepts sometimes interact--in object xfor exampleobject is looked up per scopesand then is looked up in the result objects since scopes and namespaces are essential to understanding python codelet' summarize the rules in more detail simple namesglobal unless assigned as we've learnedunqualified simple names follow the legb lexical scoping rule outlined when we explored functions in assignment ( valuemakes names local by defaultcreates or changes the name in the current local scopeunless declared global (or nonlocal in xreference (xlooks for the name in the current local scopethen any and all enclosing functionsthen the current global scopethen the built-in scopeper the legb rule enclosing classes are not searchedclass names are fetched as object attributes instead also per some special-case constructs localize names further ( variables in some comprehensions and try statement clauses)but the vast majority of names follow the legb rule attribute namesobject namespaces we've also seen that qualified attribute names refer to attributes of specific objects and obey the rules for modules and classes for class and instance objectsthe reference rules are augmented to include the inheritance search procedureassignment (object valuecreates or alters the attribute name in the namespace of the object being qualifiedand none other inheritance-tree climbing happens only on attribute referencenot on attribute assignment class coding details
1,432
for class-based objectssearches for the attribute name in objectthen in all accessible classes above itusing the inheritance search procedure for nonclass objects such as modulesfetches from object directly as noted earlierthe preceding captures the normal and typical case these attribute rules can vary in classes that utilize more advanced toolsespecially for new-style classes --an option in and the standard in xwhich we'll explore in for examplereference inheritance can be richer than implied here when metaclasses are deployedand classes which leverage attribute management tools such as propertiesdescriptorsand __setattr__ can intercept and route attribute assignments arbitrarily in factsome inheritance is run on assignment tooto locate descriptors with __set__ method in new-style classessuch tools override the normal rules for both reference and assignment we'll explore attribute management tools in depth in and formalize inheritance and its use of descriptors in for nowmost readers should focus on the normal rules given herewhich cover most python application code the "zenof namespacesassignments classify names with distinct search procedures for qualified and unqualified namesand multiple lookup layers for bothit can sometimes be difficult to tell where name will wind up going in pythonthe place where you assign name is crucial--it fully determines the scope or object in which name will reside the file manynames py illustrates how this principle translates to code and summarizes the namespace ideas we have seen throughout this book (sans obscure special-case scopes like comprehensions)file manynames py global (modulename/attribute (xor manynames xdef ()print(xaccess global ( def () print(xclass cx def (self) self local (functionvariable (xhides module xclass attribute ( xlocal variable in method (xinstance attribute (instance xthis file assigns the same namexfive times--illustrativethough not exactly best practicebecause this name is assigned in five different locationsthoughall five xs in this program are completely different variables from top to bottomthe assignments to here generatea module attribute ( ) local variable in function ( ) class namespacesthe conclusion
1,433
all five are named xthe fact that they are all assigned at different places in the source code or to different objects makes all of these unique variables you should take the time to study this example carefully because it collects ideas we've been exploring throughout the last few parts of this book when it makes sense to youyou will have achieved python namespace enlightenment oryou can run the code and see what happens--here' the remainder of this source filewhich makes an instance and prints all the xs that it can fetchmanynames pycontinued if __name__ ='__main__'print(xf( (print( module ( manynames outside file global local module name unchanged obj (print(obj xmake instance class name inherited by instance obj (print(obj xprint( xattach attribute name to instance now instance class ( obj if no in instance#print( #print( xfailsonly visible in method failsonly visible in function the outputs that are printed when the file is run are noted in the comments in the codetrace through them to see which variable named is being accessed each time notice in particular that we can go through the class to fetch its attribute ( )but we can never fetch local variables in functions or methods from outside their def statements locals are visible only to other code within the defand in fact only live in memory while call to the function or method is executing some of the names defined by this file are visible outside the file to other modules toobut recall that we must always import before we can access names in another file-name segregation is the main point of modulesafter allotherfile py import manynames print(xprint(manynames the global here globals become attributes after imports manynames (manynames ( manynames' xnot the one here local in other file' function print(manynames xi manynames (print( attribute of class in other module class coding details still from class here
1,434
print( now from instancenotice here how manynames (prints the in manynamesnot the assigned in this file --scopes are always determined by the position of assignments in your source code ( lexicallyand are never influenced by what imports what or who imports whom alsonotice that the instance' own is not created until we call ()--attributeslike all variablesspring into existence when assignedand not before normally we create instance attributes by assigning them in class __init__ constructor methodsbut this isn' the only option finallyas we learned in it' also possible for function to change names outside itselfwith global and (in python xnonlocal statements--these statements provide write accessbut also modify assignment' namespace binding rulesx global in module def ()print(xreference global in module ( def ()global change global in module def () def nested()print(xdef () def nested()nonlocal local in function reference local in enclosing scope ( local in function python statement change local in enclosing scope of courseyou generally shouldn' use the same name for every variable in your script --but as this example demonstrateseven if you dopython' namespaces will work to keep names used in one context from accidentally clashing with those used in another nested classesthe legb scopes rule revisited the preceding example summarized the effect of nested functions on scopeswhich we studied in it turns out that classes can be nested too-- useful coding pattern in some types of programswith scope implications that follow naturally from what you already knowbut that may not be obvious on first encounter this section illustrates the concept by example though they are normally coded at the top level of moduleclasses also sometimes appear nested in functions that generate them-- variation on the "factory function( closuretheme in with similar state retention roles there we noted namespacesthe conclusion
1,435
which follow the same legb scope lookup rule as function definitions this rule applies both to the top level of the class itselfas well as to the top level of method functions nested within it both form the layer in this rule--they are normal local scopeswith access to their namesnames in any enclosing functionsglobals in the enclosing moduleand built-ins like modulesthe class' local scope morphs into an attribute namespace after the class statement is run although classes have access to enclosing functionsscopesthoughthey do not act as enclosing scopes to code nested within the classpython searches enclosing functions for referenced namesbut never any enclosing classes that isa class is local scope and has access to enclosing local scopesbut it does not serve as an enclosing local scope to further nested code because the search for names used in method functions skips the enclosing classclass attributes must be fetched as object attributes using inheritance for examplein the following nester functionall references to are routed to the global scope except the lastwhich picks up local scope redefinition (the section' code is in file classscope pyand the output of each example is described in its last two comments) def nester()print(xclass cprint(xdef method (self)print(xdef method (self) print(xi ( method ( method (print(xnester(print('-'* global global global hides global local global rest watch what happensthoughwhen we reassign the same name in nested function layersthe redefinitions of create locals that hide those in enclosing scopesjust as for simple nested functionsthe enclosing class layer does not change this ruleand in fact is irrelevant to itx def nester() print(xclass cprint( class coding details hides global local in enclosing def (nester)
1,436
def method (self)print(xdef method (self) print(xi ( method ( method (print(xnester(print('-'* in enclosing def (nester) hides enclosing (nesterlocal global rest and here' what happens when we reassign the same name at multiple stops along the wayassignments in the local scopes of both functions and classes hide globals or enclosing function locals of the same nameregardless of the nesting involvedx def nester() print(xclass cx print(xdef method (self)print(xprint(self xdef method (self) print(xself print(self xi ( method ( method (print(xnester(print('-'* hides global local class local hides nester'sc or (not scopedlocal in enclosing def (not in class!) inherited class local hides enclosing (nesternot classlocal hides class located in instance global rest most importantlythe lookup rules for simple names like never search enclosing class statements--just defsmodulesand built-ins (it' the legb rulenot clegb!in method for examplex is found in def outside the enclosing class that has the same name in its local scope to get to names assigned in the class ( methods)we must fetch them as class or instance object attributesvia self in this case believe it or notwe'll see use cases for this nested classes coding pattern later in this bookespecially in some of ' decorators in this rolethe enclosing function usually both serves as class factory and provides retained state for later use in the enclosed class or its methods namespacesthe conclusion
1,437
in we learned that module namespaces have concrete implementation as dictionariesexposed with the built-in __dict__ attribute in and we learned that the same holds true for class and instance objects--attribute qualification is mostly dictionary indexing operation internallyand attribute inheritance is largely matter of searching linked dictionaries in factwithin pythoninstance and class objects are mostly just dictionaries with links between them python exposes these dictionariesas well as their linksfor use in advanced roles ( for coding toolswe put some of these tools to work in the prior but to summarize and help you better understand how attributes work internallylet' work through an interactive session that traces the way namespace dictionaries grow when classes are involved now that we know more about methods and superclasseswe can also embellish the coverage here for better look firstlet' define superclass and subclass with methods that will store data in their instancesclass superdef hello(self)self data 'spamclass sub(super)def hola(self)self data 'eggswhen we make an instance of the subclassthe instance starts out with an empty namespace dictionarybut it has links back to the class for the inheritance search to follow in factthe inheritance tree is explicitly available in special attributeswhich you can inspect instances have __class__ attribute that links to their classand classes have __bases__ attribute that is tuple containing links to higher superclasses ( ' running this on python your name formatsinternal attributesand key orders may vary) sub( __dict__ { __class__ sub __bases__ (,super __bases__ (,instance namespace dict class of instance superclasses of class (empty tuple in python as classes assign to self attributesthey populate the instance objects--that isattributes wind up in the instancesattribute namespace dictionariesnot in the classesan instance object' namespace records data that can vary from instance to instanceand self is hook into that namespacey sub( class coding details
1,438
__dict__ {'data ''spam' hola( __dict__ {'data ''eggs''data ''spam'list(sub __dict__ keys()['__qualname__''__module__''__doc__''hola'list(super __dict__ keys()['__module__''hello''__dict__''__qualname__''__doc__''__weakref__' __dict__ {notice the extra underscore names in the class dictionariespython sets these automaticallyand we can filter them out with the generator expressions we saw in and that we won' repeat here most are not used in typical programsbut there are tools that use some of them ( __doc__ holds the docstrings discussed in alsoobserve that ya second instance made at the start of this seriesstill has an empty namespace dictionary at the endeven though ' dictionary has been populated by assignments in methods againeach instance has an independent namespace dictionarywhich starts out empty and can record completely different attributes than those recorded by the namespace dictionaries of other instances of the same class because attributes are actually dictionary keys inside pythonthere are really two ways to fetch and assign their values--by qualificationor by key indexingx data __dict__['data '('spam''spam' data 'toastx __dict__ {'data ''eggs''data ''toast''data ''spam' __dict__['data ''hamx data 'hamthis equivalence applies only to attributes actually attached to the instancethough because attribute fetch qualification also performs an inheritance searchit can access inherited attributes that namespace dictionary indexing cannot the inherited attribute hellofor instancecannot be accessed by __dict__['hello'experiment with these special attributes on your own to get better feel for how namespaces actually do their attribute business also try running these objects through the dir function we met in the prior two --dir(xis similar to __dict__ keys()but dir sorts its list and includes some inherited and built-in atnamespacesthe conclusion
1,439
they are just normal dictionaries can help solidify namespaces in general in we'll learn also about slotsa somewhat advanced newstyle class feature that stores attributes in instancesbut not in their namespace dictionaries it' tempting to treat these as class attributesand indeedthey appear in class namespaces where they manage the per-instance values as we'll seethoughslots may prevent __dict__ from being created in the instance entirely-- potential that generic tools must sometimes account for by using storage-neutral tools such as dir and getattr namespace linksa tree climber the prior section demonstrated the special __class__ and __bases__ instance and class attributeswithout really explaining why you might care about them in shortthese attributes allow you to inspect inheritance hierarchies within your own code for examplethey can be used to display class treeas in the following python and example#!python ""classtree pyclimb inheritance trees using namespace linksdisplaying higher superclasses with indentation for height ""def classtree(clsindent)print(indent cls __name__for supercls in cls __bases__classtree(superclsindent+ print class name here recur to all superclasses may visit super once def instancetree(inst)print('tree of %sinstclasstree(inst __class__ show instance climb to its class def selftest()class apass class ( )pass class ( )pass class ( , )pass class epass class ( , )pass instancetree( ()instancetree( ()if __name__ ='__main__'selftest(the classtree function in this script is recursive--it prints class' name using __name__then climbs up to the superclasses by calling itself this allows the function to traverse arbitrarily shaped class treesthe recursion climbs to the topand stops at class coding details
1,440
active level of function gets its own copy of the local scopeherethis means that cls and indent are different at each classtree level most of this file is self-test code when run standalone in python xit builds an empty class treemakes two instances from itand prints their class tree structuresc:\codec:\python \python classtree py tree of tree of when run by python xthe tree includes the implied object superclass that is automatically added above standalone root ( topmostclassesbecause all classes are "new stylein --more on this change in :\codec:\python \python classtree py tree of object at object tree of object at object object object hereindentation marked by periods is used to denote class tree height of coursewe could improve on this output formatand perhaps even sketch it in gui display even as isthoughwe can import these functions anywhere we want quick display of physical class treec:\codec:\python \python class emppass class person(emp)pass bob person(import classtree classtree instancetree(bobnamespacesthe conclusion
1,441
person emp object regardless of whether you will ever code or use such toolsthis example demonstrates one of the many ways that you can make use of special attributes that expose interpreter internals you'll see another when we code the lister py general-purpose class display tools in ' section "multiple inheritance"mix-inclasseson page --therewe will extend this technique to also display attributes in each object in class tree and function as common superclass in the last part of this bookwe'll revisit such tools in the context of python tool building at largeto code tools that implement attribute privacyargument validationand more while not in every python programmer' job descriptionaccess to internals enables powerful development tools documentation strings revisited the last section' example includes docstring for its modulebut remember that docstrings can be used for class components as well docstringswhich we covered in detail in are string literals that show up at the top of various structures and are automatically saved by python in the corresponding objects__doc__ attributes this works for module filesfunction defsand classes and methods now that we know more about classes and methodsthe following filedocstr pyprovides quick but comprehensive example that summarizes the places where docstrings can show up in your code all of these can be triple-quoted blocks or simpler one-liner literals like those here" amdocstr __doc__def func(args)" amdocstr func __doc__pass class spam" amspam __doc__ or docstr spam __doc__ or self __doc__def method(self)" amspam method __doc__ or self method __doc__print(self __doc__print(self method __doc__the main advantage of documentation strings is that they stick around at runtime thusif it' been coded as docstringyou can qualify an object with its __doc__ attribute to fetch its documentation (printing the result interprets line breaks if it' multiline string)import docstr docstr __doc__ class coding details
1,442
docstr func __doc__ ' amdocstr func __doc__docstr spam __doc__ ' amspam __doc__ or docstr spam __doc__ or self __doc__docstr spam method __doc__ ' amspam method __doc__ or self method __doc__x docstr spam( method( amspam __doc__ or docstr spam __doc__ or self __doc__ amspam method __doc__ or self method __doc__ discussion of the pydoc toolwhich knows how to format all these strings in reports and web pagesappears in here it is running its help function on our code under python (python shows additional attributes inherited from the implied object superclass in the new-style class model--run this on your own to see the extrasand watch for more about this difference in )help(docstrhelp on module docstrname docstr amdocstr __doc__ file :\code\docstr py classes spam class spam amspam __doc__ or docstr spam __doc__ or self __doc__ methods defined heremethod(selfi amspam method __doc__ or self method __doc__ functions func(argsi amdocstr func __doc__ documentation strings are available at runtimebut they are less flexible syntactically than commentswhich can appear anywhere in program both forms are useful toolsand any program documentation is good (as long as it' accurateof course!as stated beforethe python "best practicerule of thumb is to use docstrings for functional documentation (what your objects doand hash-mark comments for more micro-level documentation (how arcane bits of code workdocumentation strings revisited
1,443
finallylet' wrap up this by briefly comparing the topics of this book' last two partsmodules and classes because they're both about namespacesthe distinction can be confusing in shortmodules -implement data/logic packages -are created with python files or other-language extensions -are used by being imported -form the top-level in python program structure classes -implement new full-featured objects -are created with class statements -are used by being called -always live within module classes also support extra features that modules don'tsuch as operator overloadingmultiple instance generationand inheritance although both classes and modules are namespacesyou should be able to tell by now that they are very different things we need to move ahead to see just how different classes can be summary this took us on secondmore in-depth tour of the oop mechanisms of the python language we learned more about classesmethodsand inheritanceand we wrapped up the namespaces and scopes story in python by extending it to cover its application to classes along the waywe looked at some more advanced conceptssuch as abstract superclassesclass data attributesnamespace dictionaries and linksand manual calls to superclass methods and constructors now that we've learned all about the mechanics of coding classes in python turns to specific facet of those mechanicsoperator overloading after that we'll explore common design patternslooking at some of the ways that classes are commonly used and combined to optimize code reuse before you read aheadthoughbe sure to work through the usual quiz to review what we've covered here test your knowledgequiz what is an abstract superclass what happens when simple assignment statement appears at the top level of class statement class coding details
1,444
how can you augmentinstead of completely replacingan inherited method how does class' local scope differ from that of function what was the capital of assyriatest your knowledgeanswers an abstract superclass is class that calls methodbut does not inherit or define it--it expects the method to be filled in by subclass this is often used as way to generalize classes when behavior cannot be predicted until more specific subclass is coded oop frameworks also use this as way to dispatch to client-definedcustomizable operations when simple assignment statement ( yappears at the top level of class statementit attaches data attribute to the class (class xlike all class attributesthis will be shared by all instancesdata attributes are not callable method functionsthough class must manually call the __init__ method in superclass if it defines an __init__ constructor of its own and still wants the superclass' construction code to run python itself automatically runs just one constructor--the lowest one in the tree superclass constructors are usually called through the class namepassing in the self instance manuallysuperclass __init__(self to augment instead of completely replacing an inherited methodredefine it in subclassbut call back to the superclass' version of the method manually from the new version of the method in the subclass that ispass the self instance to the superclass' version of the method manuallysuperclass method(self class is local scope and has access to enclosing local scopesbut it does not serve as an enclosing local scope to further nested code like modulesthe class local scope morphs into an attribute namespace after the class statement is run ashur (or qalat sherqat)calah (or nimrud)the short-lived dur sharrukin (or khorsabad)and finally nineveh test your knowledgeanswers
1,445
operator overloading this continues our in-depth survey of class mechanics by focusing on operator overloading we looked briefly at operator overloading in prior herewe'll fill in more details and look at handful of commonly used overloading methods although we won' demonstrate each of the many operator overloading methods availablethose we will code here are representative sample large enough to uncover the possibilities of this python class feature the basics really "operator overloadingsimply means intercepting built-in operations in class' methods--python automatically invokes your methods when instances of the class appear in built-in operationsand your method' return value becomes the result of the corresponding operation here' review of the key ideas behind overloadingoperator overloading lets classes intercept normal python operations classes can overload all python expression operators classes can also overload built-in operations such as printingfunction callsattribute accessetc overloading makes class instances act more like built-in types overloading is implemented by providing specially named methods in class in other wordswhen certain specially named methods are provided in classpython automatically calls them when instances of the class appear in their associated expressions your class provides the behavior of the corresponding operation for instance objects created from it as we've learnedoperator overloading methods are never required and generally don' have defaults (apart from handful that some classes get from object)if you don' code or inherit oneit just means that your class does not support the corresponding operation when usedthoughthese methods allow classes to emulate the interfaces of built-in objectsand so appear more consistent
1,446
as reviewconsider the following simple exampleits number classcoded in the file number pyprovides method to intercept instance construction (__init__)as well as one for catching subtraction expressions (__sub__special methods such as these are the hooks that let you tie into built-in operationsfile number py class numberdef __init__(selfstart)self data start def __sub__(selfother)return number(self data otherfrom number import number number( data on number(starton instance other result is new instance fetch class from module number __init__( number __sub__( is new number instance as we've already learnedthe __init__ constructor method seen in this code is the most commonly used operator overloading method in pythonit' present in most classesand used to initialize the newly created instance object using any arguments passed to the class name the __sub__ method plays the binary operator role that __add__ did in ' introductionintercepting subtraction expressions and returning new instance of the class as its result (and running __init__ along the waywe've already studied __init__ and basic binary operators like __sub__ in some depthso we won' rehash their usage further here in this we will tour some of the other tools available in this domain and look at example code that applies them in common use cases technicallyinstance creation first triggers the __new__ methodwhich creates and returns the new instance objectwhich is then passed into __init__ for initialization since __new__ has built-in implementation and is redefined in only very limited rolesthoughnearly all python classes initialize by defining an __init__ method we'll see one use case for __new__ when we study metaclasses in though rareit is sometimes also used to customize creation of instances of mutable types common operator overloading methods just about everything you can do to built-in objects such as integers and lists has corresponding specially named method for overloading in classes table - lists few of the most commonthere are many more in factmany overloading methods come in multiple versions ( __add____radd__and __iadd__ for addition)which operator overloading
1,447
table - common operator overloading methods method implements called for __init__ constructor object creationx class(args__del__ destructor object reclamation of __add__ operator yx + if no __iadd__ __or__ operator (bitwise orx yx | if no __ior__ __repr____str__ printingconversions print( )repr( )str(x__call__ function calls (*args**kargs__getattr__ attribute fetch undefined __setattr__ attribute assignment any value __delattr__ attribute deletion del any __getattribute__ attribute fetch any __getitem__ indexingslicingiteration [key] [ : ]for loops and other iterations if no __iter__ __setitem__ index and slice assignment [keyvaluex[ :jiterable __delitem__ index and slice deletion del [key]del [ :j__len__ length len( )truth tests if no __bool__ __bool__ boolean tests bool( )truth tests (named __nonzero__ in x__lt____gt____le____ge____eq____ne__ comparisons yx yx =yx ! (or else __cmp__ in only__radd__ right-side operators other __iadd__ in-place augmented operators + (or else __add____iter____next__ iteration contexts =iter( )next( )for loopsin if no __con tains__all comprehensionsmap( , )others (__next__ is named next in x__contains__ membership test item in (any iterable__index__ integer value hex( )bin( )oct( ) [ ] [ :(replaces __oct____hex____enter____exit__ context manager (with obj as var__get____set____delete__ descriptor attributes ( attrx attr valuedel attr __new__ creation (object creationbefore __init__ all overloading methods have names that start and end with two underscores to keep them distinct from other names you define in your classes the mappings from special the basics
1,448
and documented in full in the standard language manual and other reference resources for examplethe name __add__ always maps to expressions by python language definitionregardless of what an __add__ method' code actually does operator overloading methods may be inherited from superclasses if not definedjust like any other methods operator overloading methods are also all optional--if you don' code or inherit onethat operation is simply unsupported by your classand attempting it will raise an exception some built-in operationslike printinghave defaults (inherited from the implied object class in python )but most built-ins fail for class instances if no corresponding operator overloading method is present most overloading methods are used only in advanced programs that require objects to behave like built-insthough the __init__ constructor we've already met tends to appear in most classes let' explore some of the additional methods in table - by example although expressions trigger operator methodsbe careful not to assume that there is speed advantage to cutting out the middleman and calling the operator method directly in factcalling the operator method directly might be twice as slowpresumably because of the overhead of function callwhich python avoids or optimizes in built-in cases here' the story for len and __len__ using appendix ' windows launcher and ' timing techniques on python and in bothcalling __len__ directly takes twice as longc:\codepy - - timeit - - - " list(range( ))" __len__() loopsbest of usec per loop :\codepy - - timeit - - - " list(range( ))" len( ) loopsbest of usec per loop :\codepy - - timeit - - - " list(range( ))" __len__() loopsbest of usec per loop :\codepy - - timeit - - - " list(range( ))" len( ) loopsbest of usec per loop this is not as artificial as it may seem-- 've actually come across recommendations for using the slower alternative in the name of speed at noted research institutionindexing and slicing__getitem__ and __setitem__ our first method set allows your classes to mimic some of the behaviors of sequences and mappings if defined in class (or inherited by it)the __getitem__ method is called operator overloading
1,449
for examplethe following class returns the square of an index value--atypical perhapsbut illustrative of the mechanism in generalclass indexerdef __getitem__(selfindex)return index * indexer( [ for in range( )print( [ ]end=' [icalls __getitem__(iruns __getitem__(xieach time intercepting slices interestinglyin addition to indexing__getitem__ is also called for slice expressions-always in xand conditionally in if you don' provide more specific slicing methods formally speakingbuilt-in types handle slicing the same way herefor exampleis slicing at work on built-in listusing upper and lower bounds and stride (see if you need refresher on slicing) [ [ : [ [ :[ [:- [ [:: [ slice with slice syntax ( - reallythoughslicing bounds are bundled up into slice object and passed to the list' implementation of indexing in factyou can always pass slice object manually--slice syntax is mostly syntactic sugar for indexing with slice objectl[slice( )[ [slice( none)[ [slice(none- )[ [slice(nonenone )[ slice with slice objects this matters in classes with __getitem__ method--in xthe method will be called both for basic indexing (with an indexand for slicing (with slice objectour previous indexing and slicing__getitem__ and __setitem__
1,450
following class will when called for indexingthe argument is an integer as beforeclass indexerdata [ def __getitem__(selfindex)print('getitem:'indexreturn self data[indexx indexer( [ getitem [ getitem [- getitem- called for index or slice perform index or slice indexing sends __getitem__ an integer when called for slicingthoughthe method receives slice objectwhich is simply passed along to the embedded list indexer in new index expressionx[ : getitemslice( none[ [ :getitemslice( nonenone[ [:- getitemslice(none- none[ [:: getitemslice(nonenone [ slicing sends __getitem__ slice object where needed__getitem__ can test the type of its argumentand extract slice object bounds--slice objects have attributes startstopand stepany of which can be none if omittedclass indexerdef __getitem__(selfindex)if isinstance(indexint)test usage mode print('indexing'indexelseprint('slicing'index startindex stopindex stepx indexer( [ indexing [ : : slicing [ :slicing none none operator overloading
1,451
slice assignments--in (and usually in xit receives slice object for the latterwhich may be passed along in another index assignment or used directly in the same wayclass indexsetterdef __setitem__(selfindexvalue)self data[indexvalue intercept index or slice assignment assign index or slice in fact__getitem__ may be called automatically in even more contexts than indexing and slicing--it' also an iteration fallback optionas we'll see in moment firstthoughlet' take quick look at ' flavor of these operations for readersand clarify potential point of confusion in this category slicing and indexing in python in python onlyclasses can also define __getslice__ and __setslice__ methods to intercept slice fetches and assignments specifically if definedthese methods are passed the bounds of the slice expressionand are preferred over __getitem__ and __seti tem__ for two-limit slices in all other casesthoughthis context works the same as in xfor examplea slice object is still created and passed to __getitem__ if no __get slice__ is found or three-limit extended slice form is usedc:\codec:\python \python class slicerdef __getitem__(selfindex)print index def __getslice__(selfij)print ij def __setslice__(selfij,seq)print ij,seq slicer()[ slicer()[ : slicer()[ : : slice( runs __getitem__ with intlike runs __getslice__ if presentelse __getitem__ runs __getitem__ with slice()like xthese slice-specific methods are removed in xso even in you should generally use __getitem__ and __setitem__ instead and allow for both indexes and slice objects as arguments--both for forward compatibilityand to avoid having to handle twoand three-limit slices differently in most classesthis works without any special codebecause indexing methods can manually pass along the slice object in the square brackets of another index expressionas in the prior section' example see the section "membership__contains____iter__and __getitem__on page for another example of slice interception at work indexing and slicing__getitem__ and __setitem__
1,452
on related notedon' confuse the (perhaps unfortunately named__index__ method in python for index interception--this method returns an integer value for an instance when needed and is used by built-ins that convert to digit strings (and in retrospectmight have been better named __asindex__)class cdef __index__(self)return (hex( ' xffbin( ' oct( ' integer value although this method does not intercept instance indexing like __getitem__it is also used in contexts that require an integer--including indexing(' )[ ' (' )[ ' (' )[ :'cas index (not [ ]as index (not [ :]this method works the same way in python xexcept that it is not called for the hex and oct built-in functionsuse __hex__ and __oct__ in (onlyinstead to intercept these calls index iteration__getitem__ here' hook that isn' always obvious to beginnersbut turns out to be surprisingly useful in the absence of more-specific iteration methods we'll get to in the next sectionthe for statement works by repeatedly indexing sequence from zero to higher indexesuntil an out-of-bounds indexerror exception is detected because of that__geti tem__ also turns out to be one way to overload iteration in python--if this method is definedfor loops call the class' __getitem__ each time throughwith successively higher offsets it' case of "code oneget one free"--any built-in or user-defined object that responds to indexing also responds to for loop iterationclass stepperindexdef __getitem__(selfi)return self data[ix stepperindex( data "spam operator overloading is stepperindex object
1,453
[ 'pfor item in xprint(itemend='indexing calls __getitem__ for loops call __getitem__ for indexes items in factit' really case of "code oneget bunch free any class that supports for loops automatically supports all iteration contexts in pythonmany of which we've seen in earlier (iteration contexts were presented in for examplethe in membership testlist comprehensionsthe map built-inlist and tuple assignmentsand type constructors will also call __getitem__ automaticallyif it' defined'pin true all call __getitem__ too [ for in [' '' '' '' 'list comprehension list(map(str upperx)[' '' '' '' 'map calls (use list(in (abcdx acd (' '' '' 'sequence assignments list( )tuple( )'join(xand so on ([' '' '' '' '](' '' '' '' ')'spam' in practicethis technique can be used to create objects that provide sequence interface and to add logic to built-in sequence type operationswe'll revisit this idea when extending built-in types in iterable objects__iter__ and __next__ although the __getitem__ technique of the prior section worksit' really just fallback for iteration todayall iteration contexts in python will try the __iter__ method firstbefore trying __getitem__ that isthey prefer the iteration protocol we learned about in to repeatedly indexing an objectonly if the object does not support the iteration protocol is indexing attempted instead generally speakingyou should prefer __iter__ too--it supports general iteration contexts better than __getitem__ can technicallyiteration contexts work by passing an iterable object to the iter built-in function to invoke an __iter__ methodwhich is expected to return an iterator object if it' providedpython then repeatedly calls this iterator object' __next__ method to produce items until stopiteration exception is raised next built-in function is also iterable objects__iter__ and __next__
1,454
__next__(for review of this model' essentialssee figure - in this iterable object interface is given priority and attempted first only if no such __iter__ method is foundpython falls back on the __getitem__ scheme and repeatedly indexes by offsets as beforeuntil an indexerror exception is raised version skew noteas described in if you are using python xthe __next__(iterator method just described is named next(in your pythonand the next(ibuilt-in is present for portability--it calls next(in and __next__(in iteration works the same in in all other respects user-defined iterables in the __iter__ schemeclasses implement user-defined iterables by simply implementing the iteration protocol introduced in and elaborated in for examplethe following file uses class to define user-defined iterable that generates squares on demandinstead of all at once (per the preceding notein python define next instead of __next__and print with trailing comma as usual)file squares py class squaresdef __init__(selfstartstop)self value start self stop stop def __iter__(self)return self def __next__(self)if self value =self stopraise stopiteration self value + return self value * save state when created get iterator object on iter return square on each iteration also called by next built-in when importedits instances can appear in iteration contexts just like built-inspython from squares import squares for in squares( )print(iend='for calls iterwhich calls __iter__ each iteration calls __next__ herethe iterator object returned by __iter__ is simply the instance selfbecause the __next__ method is part of this class itself in more complex scenariosthe iterator object may be defined as separate class and object with its own state information to support multiple active iterations over the same data (we'll see an example of this in momentthe end of the iteration is signaled with python raise statement--introduced in and covered in full in the next part of this bookbut which simply operator overloading
1,455
user-defined iterables as they do on built-in types as wellx squares( iter(xnext( next( more omitted next( next(istopiteration iterate manuallywhat loops do iter calls __iter__ next calls __next__ (in xcan catch this in try statement an equivalent coding of this iterable with __getitem__ might be less naturalbecause the for would then iterate through all offsets zero and higherthe offsets passed in would be only indirectly related to the range of values produced ( would need to map to start stopbecause __iter__ objects retain explicitly managed state between next callsthey can be more general than __getitem__ on the other handiterables based on __iter__ can sometimes be more complex and less functional than those based on __getitem__ they are really designed for iterationnot random indexing--in factthey don' overload the indexing expression at allthough you can collect their items in sequence such as list to enable other operationsx squares( [ typeerror'squaresobject does not support indexing list( )[ single versus multiple scans the __iter__ scheme is also the implementation for all the other iteration contexts we saw in action for the __getitem__ method--membership teststype constructorssequence assignmentand so on unlike our prior __getitem__ examplethoughwe also need to be aware that class' __iter__ may be designed for single traversal onlynot many classes choose scan behavior explicitly in their code for examplebecause the current squares class' __iter__ always returns self with just one copy of iteration stateit is one-shot iterationonce you've iterated over an instance of that classit' empty calling __iter__ again on the same instance returns self againin whatever state it may have been left you generally need to make new iterable instance object for each new iterationx squares( [ for in [ [ for in [make an iterable with state exhausts items__iter__ returns self now it' empty__iter__ returns same self iterable objects__iter__ and __next__
1,456
[ list(squares( )[ make new iterable object new object for each new __iter__ call to support multiple iterations more directlywe could also recode this example with an extra class or other techniqueas we will in moment as isthoughby creating new instance for each iterationyou get fresh copy of iteration state in squares( true abc squares( abc ( ':join(map(strsquares( ))' : : : : other iteration contexts each calls __iter__ and then __next__ just like single-scan built-ins such as mapconverting to list supports multiple scans as wellbut adds time and space performance costswhich may or may not be significant to given programx squares( tuple( )tuple( (( )()iterator exhausted in second tuple( list(squares( )tuple( )tuple( (( )( )we'll improve this to support multiple scans more directly aheadafter bit of compareand-contrast classes versus generators notice that the preceding example would probably be simpler if it was coded with generator functions or expressions--tools introduced in that automatically produce iterable objects and retain local variable state between iterationsdef gsquares(startstop)for in range(startstop )yield * for in gsquares( )print(iend=' for in ( * for in range( ))print(iend=' unlike classesgenerator functions and expressions implicitly save their state and create the methods required to conform to the iteration protocol--with obvious advantages operator overloading
1,457
explicit attributes and methodsextra structureinheritance hierarchiesand support for multiple behaviors may be better suited for richer use cases of coursefor this artificial exampleyou could in fact skip both techniques and simply use for loopmapor list comprehension to build the list all at once barring performance data to the contrarythe best and fastest way to accomplish task in python is often also the simplest[ * for in range( )[ howeverclasses may be better at modeling more complex iterationsespecially when they can benefit from the assets of classes in general an iterable that produces items in complex database or web service resultfor examplemight be able to take fuller advantage of classes the next section explores another use case for classes in userdefined iterables multiple iterators on one object earlieri mentioned that the iterator object (with __next__produced by an iterable may be defined as separate class with its own state information to more directly support multiple active iterations over the same data consider what happens when we step across built-in type like strings 'acefor in sfor in sprint( yend='aa ac ae ca cc ce ea ec ee herethe outer loop grabs an iterator from the string by calling iterand each nested loop does the same to get an independent iterator because each active iterator has its own state informationeach loop can maintain its own position in the stringregardless of any other active loops moreoverwe're not required to make new string or convert to list each timethe single string object itself supports multiple scans we saw related examples earlierin and for instancegenerator functions and expressionsas well as built-ins like map and zipproved to be singleiterator objectsthus supporting single active scan by contrastthe range built-inand other built-in types like listssupport multiple active iterators with independent positions when we code user-defined iterables with classesit' up to us to decide whether we will support single active iteration or many to achieve the multiple-iterator effect__iter__ simply needs to define new stateful object for the iteratorinstead of returning self for each iterator request iterable objects__iter__ and __next__
1,458
other item on iterations because its iterator object is created anew from supplemental class for each iterationit supports multiple active loops directly (this is file skipper py in the book' examples)#!python file skipper py class skipobjectdef __init__(selfwrapped)self wrapped wrapped def __iter__(self)return skipiterator(self wrappedclass skipiteratordef __init__(selfwrapped)self wrapped wrapped self offset def __next__(self)if self offset >len(self wrapped)raise stopiteration elseitem self wrapped[self offsetself offset + return item if __name__ ='__main__'alpha 'abcdefskipper skipobject(alphai iter(skipperprint(next( )next( )next( )for in skipperfor in skipperprint( yend='save item to be used new iterator each time iterator state information terminate iterations else return and skip make container object make an iterator on it visit offsets for calls __iter__ automatically nested fors call __iter__ again each time each iterator has its own stateoffset quick portability noteas isthis is -only code to make it compatibleimport the print functionand either use next instead of __next__ for -only useor alias the two names in the class' scope for dual / usage (file skipper_ py in the book' examples does)#!python from __future__ import print_function class skipiteratordef __next__(self)next __next__ / compatibility / compatibility when the appropriate version is run in either pythonthis example works like the nested loops with built-in strings each active loop has its own position in the string because each obtains an independent iterator object that records its own state information operator overloading
1,459
aa ac ae ca cc ce ea ec ee by contrastour earlier squares example supports just one active iterationunless we call squares again in nested loops to obtain new objects herethere is just one skipob ject iterablewith multiple iterator objects created from it classes versus slices as beforewe could achieve similar results with built-in tools--for exampleslicing with third bound to skip itemss 'abcdeffor in [:: ]for in [:: ]print( yend='new objects on each iteration aa ac ae ca cc ce ea ec ee this isn' quite the samethoughfor two reasons firsteach slice expression here will physically store the result list all at once in memoryiterableson the other handproduce just one value at timewhich can save substantial space for large result lists secondslices produce new objectsso we're not really iterating over the same object in multiple places here to be closer to the classwe would need to make single object to step across by slicing ahead of times 'abcdefs [:: 'acefor in sfor in sprint( yend='same objectnew iterators aa ac ae ca cc ce ea ec ee this is more similar to our class-based solutionbut it still stores the slice result in memory all at once (there is no generator form of built-in slicing today)and it' only equivalent for this particular case of skipping every other item because user-defined iterables coded with classes can do anything class can dothey are much more general than this example may imply though such generality is not required in all applicationsuser-defined iterables are powerful tool--they allow us to make arbitrary objects look and feel like the other sequences and iterables we have met in this book we could use this technique with database objectfor exampleto support iterations over large database fetcheswith multiple cursors into the same query result iterable objects__iter__ and __next__
1,460
and nowfor something completely implicit--but potentially useful nonetheless in some applicationsit' possible to minimize coding requirements for user-defined iterables by combining the __iter__ method we're exploring here and the yield generator function statement we studied in because generator functions automatically save local variable state and create required iterator methodsthey fit this role welland complement the state retention and other utility we get from classes as reviewrecall that any function that contains yield statement is turned into generator function when calledit returns new generator object with automatic retention of local scope and code positionan automatically created __iter__ method that simply returns itselfand an automatically created __next__ method (next in xthat starts the function or resumes it where it last left offdef gen( )for in range( )yield * gen( __iter__(= true iter(gnext( )next( ( list(gen( )[ create generator with __iter__ and __next__ both methods exist on the same object runs __iter__generator returns itself runs __next__ (next in xiteration contexts automatically run iter and next this is still true even if the generator function with yield happens to be method named __iter__whenever invoked by an iteration context toolsuch method will return new generator object with the requisite __next__ as an added bonusgenerator functions coded as methods in classes have access to saved state in both instance attributes and local scope variables for examplethe following class is equivalent to the initial squares user-defined iterable we coded earlier in squares py file squares_yield py class squares__iter__ yield generator def __init__(selfstartstop)__next__ is automatic/implied self start start self stop stop def __iter__(self)for value in range(self startself stop )yield value * there' no need to alias next to __next__ for compatibility herebecause this method is now automated and implied by the use of yield as beforefor loops and other iteration tools iterate through instances of this class automaticallypython from squares_yield import squares for in squares( )print(iend=' operator overloading
1,461
and as usualwe can look under the hood to see how this actually works in iteration contexts running our class instance through iter obtains the result of calling __iter__ as usualbut in this case the result is generator object with an automatically created __next__ of the same sort we always get when calling generator function that contains yield the only difference here is that the generator function is automatically called on iter invoking the result object' next interface produces results on demands squares( runs __init__class saves instance state iter(sruns __iter__returns generator next( next(iruns generator' __next__ etc next(igenerator has both instance and local scope state stopiteration it may also help to notice that we could name the generator method something other than __iter__ and call manually to iterate--squares( , gen()for example using the __iter__ name invoked automatically by iteration tools simply skips manual attribute fetch and call stepclass squaresnon __iter__ equivalent (squares_manual pydef __init__)def gen(self)for value in range(self startself stop )yield value * python from squares_manual import squares for in squares( gen()print(iend='same results squares( iter( gen()next(isame results call generator manually for iterable/iterator coding the generator as __iter__ instead cuts out the middleman in your codethough both schemes ultimately wind up creating new generator object for each iterationwith __iter__iteration triggers __iter__which returns new generator with __next__ iterable objects__iter__ and __next__
1,462
__iter__ see for more on yield and generators if this is puzzlingand compare it with the more explicit __next__ version in squares py earlier you'll notice that this new squares_yield py version is lines shorter ( versus in sensethis scheme reduces class coding requirements much like the closure functions of but in this case does so with combination of functional and oop techniquesinstead of an alternative to classes for examplethe generator method still leverages self attributes this may also very well seem like one too many levels of magic to some observers--it relies on both the iteration protocol and the object creation of generatorsboth of which are highly implicit (in contradiction of longstanding python themessee import thisopinions asideit' important to understand the non-yield flavor of class iterables toobecause it' explicitgeneraland sometimes broader in scope stillthe __iter__/yield technique may prove effective in cases where it applies it also comes with substantial advantage--as the next section explains multiple iterators with yield besides its code concisenessthe user-defined class iterable of the prior section based upon the __iter__/yield combination has an important added bonus--it also supports multiple active iterators automatically this naturally follows from the fact that each call to __iter__ is call to generator functionwhich returns new generator with its own copy of the local scope for state retentionpython from squares_yield import squares squares( iter(snext( )next( iter(snext( next( using the __iter__/yield squares with yieldmultiple iterators automatic is independent of jown local state although generator functions are single-scan iterablesthe implicit calls to __iter__ in iteration contexts make new generators supporting new independent scanss squares( for in seach for calls __iter__ for in sprint('% :% (ij)end=' : : : : : : : : : operator overloading
1,463
explicitly and manuallyusing techniques of the preceding section (and grows to lines more than with yield)file squares_nonyield py class squaresdef __init__(selfstartstop)self start start self stop stop def __iter__(self)return squaresiter(self startself stopnon-yield generator multiscansextra object class squaresiterdef __init__(selfstartstop)self value start self stop stop def __next__(self)if self value =self stopraise stopiteration self value + return self value * this works the same as the yield multiscan versionbut with moreand more explicitcodepython from squares_nonyield import squares for in squares( )print(iend=' squares( iter(snext( )next( iter(snext( next( multiple iterators without yield squares( for in seach for calls __iter___ for in sprint('% :% (ij)end=' : : : : : : : : : finallythe generator-based approach could similarly remove the need for an extra iterator class in the prior item-skipper example of file skipper pythanks to its automatic methods and local variable state retention (and checks in at lines versus the original' )iterable objects__iter__ and __next__
1,464
class skipobjectdef __init__(selfwrapped)self wrapped wrapped def __iter__(self)offset while offset len(self wrapped)item self wrapped[offsetoffset + yield item another __iter__ yield generator instance scope retained normally local scope state saved auto this works the same as the non-yield multiscan versionbut with lessand less explicitcodepython from skipper_yield import skipobject skipper skipobject('abcdef' iter(skippernext( )next( )next( ' ' 'efor in skippereach for calls __iter__new auto generator for in skipperprint( yend='aa ac ae ca cc ce ea ec ee of coursethese are all artificial examples that could be replaced with simpler tools like comprehensionsand their code may or may not scale up in kind to more realistic tasks study these alternatives to see how they compare as so often in programmingthe best tool for the job will likely be the best tool for your jobmembership__contains____iter__and __getitem__ the iteration story is even richer than we've seen thus far operator overloading is often layeredclasses may provide specific methodsor more general alternatives used as fallback options for examplecomparisons in python use specific methods such as __lt__ for "less thanif presentor else the general __cmp__ python uses only specific methodsnot __cmp__as discussed later in this boolean tests similarly try specific __bool__ first (to give an explicit true/false result)and if it' absent fall back on the more general __len__ ( nonzero length means trueas we'll also see later in this python works the same but uses the name __nonzero__ instead of __bool__ in the iterations domainclasses can implement the in membership operator as an iterationusing either the __iter__ or __getitem__ methods to support more specific membershipthoughclasses may code __contains__ method--when presentthis operator overloading
1,465
tains__ method should define membership as applying to keys for mapping (and can use quick lookups)and as search for sequences consider the following classwhose file has been instrumented for dual / usage using the techniques described earlier it codes all three methods and tests membership and various iteration contexts applied to an instance its methods print trace messages when calledfile contains py from __future__ import print_function / compatibility class itersdef __init__(selfvalue)self data value def __getitem__(selfi)print('get[% ]:iend=''return self data[ifallback for iteration also for indexslice def __iter__(self)print('iter='end=''self ix return self preferred for iteration allows only one active iterator def __next__(self)print('next:'end=''if self ix =len(self data)raise stopiteration item self data[self ixself ix + return item def __contains__(selfx)print('contains'end=''return in self data next __next__ if __name__ ='__main__' iters([ ]print( in xfor in xprint(iend='print(print([ * for in ]printlist(map(binx)preferred for 'in / compatibility make instance membership for loops other iteration contexts iter(xmanual iteration (what other contexts dowhile truetryprint(next( )end='except stopiterationbreak membership__contains____iter__and __getitem__
1,466
scan can be active at any point in time ( nested loops won' work)because each iteration attempt resets the scan cursor to the front now that you know about yield in iteration methodsyou should be able to tell that the following is equivalent but allows multiple active scans--and judge for yourself whether its more implicit nature is worth the nested-scan support and six lines shaved (this is in file contains_yield py)class itersdef __init__(selfvalue)self data value def __getitem__(selfi)print('get[% ]:iend=''return self data[ifallback for iteration also for indexslice def __iter__(self)print('iter=next:'end=''for in self datayield print('next:'end=''preferred for iteration allows multiple active iterators no __next__ to alias to next def __contains__(selfx)print('contains'end=''return in self data preferred for 'inon both python and xwhen either version of this file runs its output is as follows --the specific __contains__ intercepts membershipthe general __iter__ catches other iteration contexts such that __next__ (whether explicitly coded or implied by yieldis called repeatedlyand __getitem__ is never calledcontainstrue iter=next: next: next: next: next: nextiter=next:next:next:next:next:next:[ iter=next:next:next:next:next:next:[' '' '' '' '' 'iter=next: next: next: next: next: nextwatch what happens to this code' output if we comment out its __contains__ methodthough--membership is now routed to the general __iter__ insteaditer=next:next:next:true iter=next: next: next: next: next: nextiter=next:next:next:next:next:next:[ iter=next:next:next:next:next:next:[' '' '' '' '' 'iter=next: next: next: next: next: nextand finallyhere is the output if both __contains__ and __iter__ are commented out --the indexing __getitem__ fallback is called with successively higher indexes until it raises indexerrorfor membership and other iteration contextsget[ ]:get[ ]:get[ ]:true get[ ]: get[ ]: get[ ]: get[ ]: get[ ]: get[ ]get[ ]:get[ ]:get[ ]:get[ ]:get[ ]:get[ ]:[ get[ ]:get[ ]:get[ ]:get[ ]:get[ ]:get[ ]:[' '' '' '' ',' 'get[ ]: get[ ]: get[ ]: get[ ]: get[ ]: get[ ] operator overloading
1,467
intercepts explicit indexing as well as slicing slice expressions trigger __getitem__ with slice object containing boundsboth for built-in types and user-defined classesso slicing is automatic in our classfrom contains import iters iters('spam' [ get[ ]:'sindexing __getitem__( 'spam'[ :'pam'spam'[slice( none)'pamslice syntax [ :get[slice( nonenone)]:'pamx[:- get[slice(none- none)]:'spa__getitem__(slice)slice object list(xand iteration tooiter=next:next:next:next:next:[' '' '' '' 'in more realistic iteration use cases that are not sequence-orientedthoughthe __iter__ method may be easier to write since it must not manage an integer indexand __contains__ allows for membership optimization as special case attribute access__getattr__ and __setattr__ in pythonclasses can also intercept basic attribute access ( qualificationwhen needed or useful specificallyfor an object created from classthe dot operator expression object attribute can be implemented by your code toofor referenceassignmentand deletion contexts we saw limited example in this category in but will review and expand on the topic here attribute reference the __getattr__ method intercepts attribute references it' called with the attribute name as string whenever you try to qualify an instance with an undefined (nonexistentattribute name it is not called if python can find the attribute using its inheritance tree search procedure because of its behavior__getattr__ is useful as hook for responding to attribute requests in generic fashion it' commonly used to delegate calls to embedded (or "wrapped"objects from proxy controller object--of the sort introduced in ' introduction to delegation this method can also be used to adapt classes to an interfaceor add accessors for data attributes after the fact--logic in method that validates or computes an attribute after it' already being used with simple dot notation attribute access__getattr__ and __setattr__
1,468
the basic mechanism underlying these goals is straightforward--the following class catches attribute referencescomputing the value for one dynamicallyand triggering an error for others unsupported with the raise statement described earlier in this for iterators (and fully covered in part vii)class emptydef __getattr__(selfattrname)if attrname ='age'return elseraise attributeerror(attrnameon self undefined empty( age name error text omitted attributeerrorname herethe empty class and its instance have no real attributes of their ownso the access to age gets routed to the __getattr__ methodself is assigned the instance ( )and attrname is assigned the undefined attribute name string ('age'the class makes age look like real attribute by returning real value as the result of the age qualification expression ( in effectage becomes dynamically computed attribute--its value is formed by running codenot fetching an object for attributes that the class doesn' know how to handle__getattr__ raises the builtin attributeerror exception to tell python that these are bona fide undefined namesasking for name triggers the error you'll see __getattr__ again when we see delegation and properties at work in the next two let' move on to related tools here attribute assignment and deletion in the same departmentthe __setattr__ intercepts all attribute assignments if this method is defined or inheritedself attr value becomes self __setattr__('attr'valuelike __getattr__this allows your class to catch attribute changesand validate or transform as desired this method is bit trickier to usethoughbecause assigning to any self attributes within __setattr__ calls __setattr__ againpotentially causing an infinite recursion loop (and fairly quick stack overflow exception!in factthis applies to all self attribute assignments anywhere in the class--all are routed to __setattr__even those in other methodsand those to names other than that which may have triggered __setattr__ in the first place rememberthis catches all attribute assignments if you wish to use this methodyou can avoid loops by coding instance attribute assignments as assignments to attribute dictionary keys that isuse self __dict__['name'xnot self name xbecause you're not assigning to __dict__ itselfthis avoids the loop operator overloading
1,469
def __setattr__(selfattrvalue)if attr ='age'self __dict__[attrvalue not self name=val or setattr elseraise attributeerror(attr not allowed' accesscontrol( age age name 'bobtext omitted attributeerrorname not allowed calls __setattr__ if you change the __dict__ assignment in this to either of the followingit triggers the infinite recursion loop and exception--both dot notation and its setattr built-in function equivalent (the assignment analog of getattrfail when age is assigned outside the classself age value setattr(selfattrvalue loops loops (attr is 'age'an assignment to another name within the class triggers recursive __setattr__ call toothough in this class ends less dramatically in the manual attributeerror exceptionself other recurs but doesn' loopfails it' also possible to avoid recursive loops in class that uses __setattr__ by routing any attribute assignments to higher superclass with callinstead of assigning keys in __dict__self __dict__[attrvalue object __setattr__(selfattrvalue okdoesn' loop okdoesn' loop (new-style onlybecause the object form requires use of new-style classes in xthoughwe'll postpone details on this form until ' deeper look at attribute management at large third attribute management method__delattr__is passed the attribute name string and invoked on all attribute deletions ( del object attrlike __setattr__it must avoid recursive loops by routing attribute deletions with the using class through __dict__ or superclass as we'll learn in attributes implemented with new-style class features such as slots and properties are not physically stored in the instance' __dict__ namespace dictionary (and slots may even preclude its existence entirely!because of thiscode that wishes to support such attributes should code __setattr__ to assign with the object __setattr__ scheme shown herenot by self __dict__ indexing unless it' known that subject classes store all their data in the instance itself in we'll also see that the new-style __getattribute__ attribute access__getattr__ and __setattr__
1,470
also applies to if new-style classes are used other attribute management tools these three attribute-access overloading methods allow you to control or specialize access to attributes in your objects they tend to play highly specialized rolessome of which we'll explore later in this book for another example of __getattr__ at worksee ' person-composite py and for future referencekeep in mind that there are other ways to manage attribute access in pythonthe __getattribute__ method intercepts all attribute fetchesnot just those that are undefinedbut when using it you must be more cautious than with __get attr__ to avoid loops the property built-in function allows us to associate methods with fetch and set operations on specific class attribute descriptors provide protocol for associating __get__ and __set__ methods of class with accesses to specific class attribute slots attributes are declared in classes but create implicit storage in each instance because these are somewhat advanced tools not of interest to every python programmerwe'll defer look at properties until and detailed coverage of all the attribute management techniques until emulating privacy for instance attributespart as another use case for such toolsthe following code--file private py--generalizes the previous exampleto allow each subclass to have its own list of private names that cannot be assigned to its instances (and uses user-defined exception classwhich you'll have to take on faith until part vii)class privateexc(exception)pass class privacydef __setattr__(selfattrnamevalue)if attrname in self privatesraise privateexc(attrnameselfelseself __dict__[attrnamevalue more on exceptions in part vii on self attrname value makeraise user-define except avoid loops by using dict key class test (privacy)privates ['age'class test (privacy)privates ['name''pay'def __init__(self)self __dict__['name''tom operator overloading to do bettersee
1,471
test ( test ( name 'bob# name 'sueprint( nameworks fails age # age print( ageworks fails in factthis is first-cut solution for an implementation of attribute privacy in python --disallowing changes to attribute names outside class although python doesn' support private declarations per setechniques like this can emulate much of their purpose this is partial--and even clumsy--solutionthoughto make it more effectivewe must augment it to allow classes to set their private attributes more naturallywithout having to go through __dict__ each timeas the constructor must do here to avoid triggering __setattr__ and an exception better and more complete approach might require wrapper ("proxy"class to check for private attribute accesses made outside the class onlyand __getattr__ to validate attribute fetches too we'll postpone more complete solution to attribute privacy until where we'll use class decorators to intercept and validate attributes more generally even though privacy can be emulated this waythoughit almost never is in practice python programmers are able to write large oop frameworks and applications without private declarations--an interesting finding about access controls in general that is beyond the scope of our purposes here stillcatching attribute references and assignments is generally useful techniqueit supports delegationa design technique that allows controller objects to wrap up embedded objectsadd new behaviorsand route other operations back to the wrapped objects because they involve design topicswe'll revisit delegation and wrapper classes in the next string representation__repr__ and __str__ our next methods deal with display formats-- topic we've already explored in prior but will summarize and formalize here as reviewthe following code exercises the __init__ constructor and the __add__ overload methodboth of which we've already seen (is an in-place operation herejust to show that it can beper named method may be preferredas we've learnedthe default display of instance objects for class like this is neither generally useful nor aesthetically prettyclass adderdef __init__(selfvalue= )self data value initialize data string representation__repr__ and __str__
1,472
self data +other adder(print(xx add other in place (bad form?default displays but coding or inheriting string representation methods allows us to customize the display--as in the followingwhich defines __repr__ method in subclass that returns string representation for its instances class addrepr(adder)def __repr__(self)return 'addrepr(% )self data inherit __init____add__ add string representation convert to as-code string addrepr( addrepr( print(xaddrepr( str( )repr( ('addrepr( )''addrepr( )'runs __init__ runs __add__ ( add(better?runs __repr__ runs __repr__ runs __repr__ for both if defined__repr__ (or its close relative__str__is called automatically when class instances are printed or converted to strings these methods allow you to define better display format for your objects than the default instance display here__repr__ uses basic string formatting to convert the managed self data object to more humanfriendly string for display why two display methodsso farwhat we've seen is largely review but while these methods are generally straightforward to usetheir roles and behavior have some subtle implications both for design and coding in particularpython provides two display methods to support alternative displays for different audiences__str__ is tried first for the print operation and the str built-in function (the internal equivalent of which print runsit generally should return user-friendly display __repr__ is used in all other contextsfor interactive echoesthe repr functionand nested appearancesas well as by print and str if no __str__ is present it should generally return an as-code string that could be used to re-create the objector detailed display for developers that is__repr__ is used everywhereexcept by print and str when __str__ is defined this means you can code __repr__ to define single display format used everywhere operator overloading
1,473
alternative display for them as noted in general tools may also prefer __str__ to leave other classes the option of adding an alternative __repr__ display for use in other contextsas long as print and str displays suffice for the tool converselya general tool that codes __repr__ still leaves clients the option of adding alternative displays with __str__ for print and str in other wordsif you code eitherthe other is available for an additional display in cases where the choice isn' clear__str__ is generally preferred for larger user-friendly displaysand __repr__ for lower-level or as-code displays and all-inclusive roles let' write some code to illustrate these two methodsdistinctions in more concrete terms the prior example in this section showed how __repr__ is used as the fallback option in many contexts howeverwhile printing falls back on __repr__ if no __str__ is definedthe inverse is not true--other contextssuch as interactive echoesuse __repr__ only and don' try __str__ at allclass addstr(adder)def __str__(self)return '[value% ]self data __str__ but no __repr__ convert to nice string addstr( default __repr__ print(xruns __str__ [value str( )repr( ('[value ]'''because of this__repr__ may be best if you want single display for all contexts by defining both methodsthoughyou can support different displays in different contexts --for examplean end-user display with __str__and low-level display for programmers to use during development with __repr__ in effect__str__ simply overrides __repr__ for more user-friendly display contextsclass addboth(adder)def __str__(self)return '[value% ]self data def __repr__(self)return 'addboth(% )self data addboth( addboth( print( [value str( )repr( ('[value ]''addboth( )'user-friendly string as-code string runs __repr__ runs __str__ string representation__repr__ and __str__
1,474
though generally simple to usei should mention three usage notes regarding these methods here firstkeep in mind that __str__ and __repr__ must both return stringsother result types are not converted and raise errorsso be sure to run them through to-string converter ( str or %if needed seconddepending on container' string-conversion logicthe user-friendly display of __str__ might only apply when objects appear at the top level of print operationobjects nested in larger objects might still print with their __repr__ or its default the following illustrates both of these pointsclass printerdef __init__(selfval)self val val def __str__(self)return str(self valobjs [printer( )printer( )for in objsprint(xused for instance itself convert to string result __str__ run when instance printed but not when instance is in list print(objs[objs [to ensure that custom display is run in all contexts regardless of the containercode __repr__not __str__the former is run in all cases if the latter doesn' applyincluding nested appearancesclass printerdef __init__(selfval)self val val def __repr__(self)return str(self val__repr__ used by print if no __str__ __repr__ used if echoed or nested objs [printer( )printer( )for in objsprint(xno __str__runs __repr__ print(objs[ objs [ runs __repr__not ___str__ thirdand perhaps most subtlethe display methods also have the potential to trigger infinite recursion loops in rare contexts--because some objectsdisplays include displays of other objectsit' not impossible that display may trigger display of an object being displayedand thus loop this is rare and obscure enough to skip herebut watch operator overloading
1,475
end of the next in its listinherited py example' classwhere __repr__ can loop in practice__str__and its more inclusive relative __repr__seem to be the second most commonly used operator overloading methods in python scriptsbehind __init__ anytime you can print an object and see custom displayone of these two tools is probably in use for additional examples of these tools at work and the design tradeoffs they implysee ' case study and ' class lister mix-insas well as their role in ' exception classeswhere __str__ is required over __repr__ right-side and in-place uses__radd__ and __iadd__ our next group of overloading methods extends the functionality of binary operator methods such as __add__ and __sub__ (called for and -)which we've already seen as mentioned earlierpart of the reason there are so many operator overloading methods is because they come in multiple flavors--for every binary expressionwe can implement leftrightand in-place variant though defaults are also applied if you don' code all threeyour objectsroles dictate how many variants you'll need to code right-side addition for instancethe __add__ methods coded so far technically do not support the use of instance objects on the right side of the operatorclass adderdef __init__(selfvalue= )self data value def __add__(selfother)return self data other adder( typeerrorunsupported operand type(sfor +'intand 'adderto implement more general expressionsand hence support commutative-style operatorscode the __radd__ method as well python calls __radd__ only when the object on the right side of the is your class instancebut the object on the left is not an instance of your class the __add__ method for the object on the left is called instead in all other cases (all of this section' five commuter classes are coded in file commuter py in the book' examplesalong with self-test)class commuter def __init__(selfval)self val val def __add__(selfother)print('add'self valotherright-side and in-place uses__radd__ and __iadd__
1,476
def __radd__(selfother)print('radd'self valotherreturn other self val from commuter import commuter commuter ( commuter ( __add__instance noninstance add __radd__noninstance instance radd __add__instance instancetriggers __radd__ add radd notice how the order is reversed in __radd__self is really on the right of the +and other is on the left also note that and are instances of the same class herewhen instances of different classes appear mixed in an expressionpython prefers the class of the one on the left when we add the two instances togetherpython runs __add__which in turn triggers __radd__ by simplifying the left operand reusing __add__ in __radd__ for truly commutative operations that do not require special-casing by positionit is also sometimes sufficient to reuse __add__ for __radd__either by calling __add__ directlyby swapping order and re-adding to trigger __add__ indirectlyor by simply assigning __radd__ to be an alias for __add__ at the top level of the class statement ( in the class' scopethe following alternatives implement all three of these schemesand return the same results as the original--though the last saves an extra call or dispatch and hence may be quicker (in all__radd__ is run when self is on the right side of +)class commuter def __init__(selfval)self val val def __add__(selfother)print('add'self valotherreturn self val other def __radd__(selfother)return self __add__(otherclass commuter def __init__(selfval)self val val def __add__(selfother)print('add'self valotherreturn self val other def __radd__(selfother) operator overloading call __add__ explicitly
1,477
return self other class commuter def __init__(selfval)self val val def __add__(selfother)print('add'self valotherreturn self val other __radd__ __add__ aliascut out the middleman in all theseright-side instance appearances trigger the singleshared __add__ methodpassing the right operand to selfto be treated the same as left-side appearance run these on your own for more insighttheir returned values are the same as the original propagating class type in more realistic classes where the class type may need to be propagated in resultsthings can become trickiertype testing may be required to tell whether it' safe to convert and thus avoid nesting for instancewithout the isinstance test in the followingwe could wind up with commuter whose val is another commuter when two instances are added and __add__ triggers __radd__class commuter def __init__(selfval)self val val def __add__(selfother)if isinstance(othercommuter )other other val return commuter (self val otherdef __radd__(selfother)return commuter (other self valdef __str__(self)return 'self val from commuter import commuter commuter ( commuter ( print( print( yz print(zprint( print( zprint( propagate class type in results type test to avoid object nesting else result is another commuter result is another commuter instance not nesteddoesn' recur to __radd__ the need for the isinstance type test here is very subtle--uncommentrunand trace to see why it' required if you doyou'll see that the last part of the preceding test right-side and in-place uses__radd__ and __iadd__
1,478
pointless recursive calls to simplify their valuesand extra constructor calls build resultsz with isinstance test commented-out print(zprint( print( zprint( to testthe rest of commuter py looks and runs like this--classes can appear in tuples naturally#!python from __future__ import print_function classes defined here / compatibility if __name__ ='__main__'for klass in (commuter commuter commuter commuter commuter )print('- klass( klass( print( print( yprint( yc:\codecommuter py add radd add radd etc there are too many coding variations to explore hereso experiment with these classes on your own for more insightaliasing __radd__ to __add__ in commuter for examplesaves linebut doesn' prevent object nesting without isinstance see also python' manuals for discussion of other options in this domainfor exampleclasses may also return the special notimplemented object for unsupported operands to influence method selection (this is treated as though the method were not definedin-place addition to also implement +in-place augmented additioncode either an __iadd__ or an __add__ the latter is used if the former is absent in factthe prior section' commuter operator overloading
1,479
manually the __iadd__ methodthoughallows for more efficient in-place changes to be coded where applicableclass numberdef __init__(selfval)self val val def __iadd__(selfother)self val +other return self __iadd__ explicitx + usually returns self number( + + val for mutable objectsthis method can often specialize for quicker in-place changesy number([ ] +[ +[ val [ in-place change faster than the normal __add__ method is run as fallbackbut may not be able optimize in-place casesclass numberdef __init__(selfval)self val val def __add__(selfother)return number(self val otherx number( + + val __add__ fallbackx ( ypropagates class type and +does concatenation here though we've focused on herekeep in mind that every binary operator has similar right-side and in-place overloading methods that work the same ( __mul____rmul__and __imul__stillright-side methods are an advanced topic and tend to be fairly uncommon in practiceyou only code them when you need operators to be commutativeand then only if you need to support such operators at all for instancea vector class may use these toolsbut an employee or button class probably would not call expressions__call__ on to our next overloading methodthe __call__ method is called when your instance is called nothis isn' circular definition--if definedpython runs __call__ method for function call expressions applied to your instancespassing along whatever posicall expressions__call__
1,480
class calleedef __call__(self*pargs**kargs)print('called:'pargskargsc callee( ( called( { ( = = called( {' ' ' ' intercept instance calls accept arbitrary arguments is callable object more formallyall the argument-passing modes we explored in are supported by the __call__ method--whatever is passed to the instance is passed to this methodalong with the usual implied instance argument for examplethe method definitionsclass cdef __call__(selfabc= = )normals and defaults class cdef __call__(self*pargs**kargs)collect arbitrary arguments class cdef __call__(self*pargsd= **kargs) keyword-only argument all match all the following instance callsx ( ( ( ( = = = (*[ ]**dict( = = ) ( *( ,) = **dict( = )omit defaults positionals keywords unpack arbitrary arguments mixed modes see for refresher on function arguments the net effect is that classes and instances with __call__ support the exact same argument syntax and semantics as normal functions and methods intercepting call expression like this allows class instances to emulate the look and feel of things like functionsbut also retain state information for use during calls we saw an example similar to the following while exploring scopes in but you should now be familiar enough with operator overloading to understand this pattern betterclass proddef __init__(selfvalue)self value value def __call__(selfother)return self value other prod( ( operator overloading accept just one argument "remembers in state (passed (state
1,481
in this examplethe __call__ may seem bit gratuitous at first glance simple method can provide similar utilityclass proddef __init__(selfvalue)self value value def comp(selfother)return self value other prod( comp( comp( however__call__ can become more useful when interfacing with apis ( librariesthat expect functions--it allows us to code objects that conform to an expected function call interfacebut also retain state informationand other class assets such as inheritance in factit may be the third most commonly used operator overloading methodbehind the __init__ constructor and the __str__ and __repr__ display-format alternatives function interfaces and callback-based code as an examplethe tkinter gui toolkit (named tkinter in python xallows you to register functions as event handlers ( callbacks)--when events occurtkinter calls the registered objects if you want an event handler to retain state between eventsyou can register either class' bound methodor an instance that conforms to the expected interface with __call__ in the prior section' codefor exampleboth comp from the second example and from the first can pass as function-like objects this way ' closure functions with state in enclosing scopes can achieve similar effectsbut don' provide as much support for multiple operations or customization 'll have more to say about bound methods in the next but for nowhere' hypothetical example of __call__ applied to the gui domain the following class defines an object that supports function-call interfacebut also has state information that remembers the color button should change to when it is later pressedclass callbackdef __init__(selfcolor)self color color def __call__(self)print('turn'self colorfunction state information support calls with no arguments call expressions__call__
1,482
for buttonseven though the gui expects to be able to invoke event handlers as simple functions with no argumentshandlers cb callback('blue'cb callback('green' button(command=cb button(command=cb remember blue remember green register handlers when the button is later pressedthe instance object is called as simple function with no argumentsexactly like in the following calls because it retains state as instance attributesthoughit remembers what to do--it becomes stateful function objectevents cb (cb (prints 'turn blueprints 'turn greenin factmany consider such classes to be the best way to retain state information in the python language (per generally accepted pythonic principlesat leastwith oopthe state remembered is made explicit with attribute assignments this is different than other state retention techniques ( global variablesenclosing function scope referencesand default mutable arguments)which rely on more limited or implicit behavior moreoverthe added structure and customization in classes goes beyond state retention on the other handtools such as closure functions are useful in basic state retention roles tooand ' nonlocal statement makes enclosing scopes viable alternative in more programs we'll revisit such tradeoffs when we start coding substantial decorators in but here' quick closure equivalentdef callback(color)def oncall()print('turn'colorreturn oncall enclosing scope versus attrs cb callback('yellow'cb (handler to be registered on eventprints 'turn yellowbefore we move onthere are two other ways that python programmers sometimes tie information to callback function like this one option is to use default arguments in lambda functionscb (lambda color='red''turn colordefaults retain state too print(cb ()the other is to use bound methods of class- bit of previewbut simple enough to introduce here bound method object is kind of object that remembers both the self instance and the referenced function this object may therefore be called later as simple function without an instance operator overloading
1,483
def __init__(selfcolor)self color color def changecolor(self)print('turn'self colorclass with state information normal named method cb callback('blue'cb callback('yellow' button(command=cb changecolorb button(command=cb changecolorbound methodreferencedon' call remembers function self pair in this casewhen this button is later pressed it' as if the gui does thiswhich invokes the instance' changecolor method to process the object' state informationinstead of the instance itselfcb callback('blue'obj cb changecolor obj(registered event handler on event prints 'turn bluenote that lambda is not required herebecause bound method reference by itself already defers call until later this technique is simplerbut perhaps less general than overloading calls with __call__ againwatch for more about bound methods in the next you'll also see another __call__ example in where we will use it to implement something known as function decorator-- callable object often used to add layer of logic on top of an embedded function because __call__ allows us to attach state information to callable objectit' natural implementation technique for function that must remember to call another function when called itself for more __call__ examplessee the state retention preview examples in and the more advanced decorators and metaclasses of and comparisons__lt____gt__and others our next batch of overloading methods supports comparisons as suggested in table - classes can define methods to catch all six comparison operators===and !these methods are generally straightforward to usebut keep the following qualifications in mindunlike the __add__/__radd__ pairings discussed earlierthere are no right-side variants of comparison methods insteadreflective methods are used when only one operand supports comparison ( __lt__ and __gt__ are each other' reflectionthere are no implicit relationships among the comparison operators the truth of =does not imply that !is falsefor exampleso both __eq__ and __ne__ should be defined to ensure that both operators behave correctly in python xa __cmp__ method is used by all comparisons if no more specific comparison methods are definedit returns number that is less thanequal toor comparisons__lt____gt__and others
1,484
the cmp(xybuilt-in to compute its result both the __cmp__ method and the cmp built-in function are removed in python xuse the more specific methods instead we don' have space for an in-depth exploration of comparison methodsbut as quick introductionconsider the following class and test codeclass cdata 'spamdef __gt__(selfother)return self data other def __lt__(selfother)return self data other (print( 'ham'print( 'ham' and version true (runs __gt__false (runs __lt__when run under python or xthe prints at the end display the expected results noted in their commentsbecause the class' methods intercept and implement comparison expressions consult python' manuals and other reference resources for more details in this categoryfor example__lt__ is used for sorts in python xand as for binary expression operatorsthese methods can also return notimplemented for unsupported arguments the __cmp__ method in python in python onlythe __cmp__ method is used as fallback if more specific methods are not definedits integer result is used to evaluate the operator being run the following produces the same result as the prior section' code under xfor examplebut fails in because __cmp__ is no longer usedclass cdata 'spamdef __cmp__(selfother)return cmp(self dataother only __cmp__ not used in cmp not defined in (print( 'ham'print( 'ham'true (runs __cmp__false (runs __cmp__notice that this fails in because __cmp__ is no longer specialnot because the cmp built-in function is no longer present if we change the prior class to the following to try to simulate the cmp callthe code still works in but fails in xclass cdata 'spamdef __cmp__(selfother)return (self data other(self data other operator overloading
1,485
supported in xwhile it would be easier to erase history entirelythis book is designed to support both and readers because __cmp__ may appear in code readers must reuse or maintainit' fair game in this book moreover__cmp__ was removed more abruptly than the __getslice__ method described earlierand so may endure longer if you use xthoughor care about running your code under in the futuredon' use __cmp__ anymoreuse the more specific comparison methods instead boolean tests__bool__ and __len__ the next set of methods is truly useful (yespun intended!as we've learnedevery object is inherently true or false in python when you code classesyou can define what this means for your objects by coding methods that give the true or false values of instances on request the names of these methods differ per python linethis section starts with the storythen shows ' equivalent as mentioned briefly earlierin boolean contextspython first tries __bool__ to obtain direct boolean valueif that method is missingpython tries __len__ to infer truth value from the object' length the first of these generally uses object state or other information to produce boolean result in xclass truthdef __bool__(self)return true truth(if xprint('yes!'yesclass truthdef __bool__(self)return false truth(bool(xfalse if this method is missingpython falls back on length because nonempty object is considered true ( nonzero length is taken to mean the object is trueand zero length means it is false)class truthdef __len__(self)return truth(if not xprint('no!'noif both methods are present python prefers __bool__ over __len__because it is more specificboolean tests__bool__ and __len__
1,486
def __bool__(self)return true def __len__(self)return tries __bool__ first tries __len__ first truth(if xprint('yes!'yesif neither truth method is definedthe object is vacuously considered true (though any potential implications for more metaphysically inclined readers are strictly coincidental)class truthpass truth(bool(xtrue at least that' the truth in these examples won' generate exceptions in xbut some of their results there may look bit odd (and trigger an existential crisis or twounless you read the next section boolean methods in python alasit' not nearly as dramatic as billed--python users simply use __nonzero__ instead of __bool__ in all of the preceding section' code python renamed the __nonzero__ method to __bool__but boolean tests work the same otherwiseboth and use __len__ as fallback subtlyif you don' use the namethe first test in the prior section will work the same for you anyhowbut only because __bool__ is not recognized as special method name in xand objects are considered true by defaultto witness this version difference liveyou need to return falsec:\codec:\python \python class cdef __bool__(self)print('in bool'return false (bool(xin bool false if xprint( in bool this works as advertised in in xthough__bool__ is ignored and the object is always considered true by default operator overloading
1,487
class cdef __bool__(self)print('in bool'return false (bool(xtrue if xprint( the short story herein xuse __nonzero__ for boolean valuesor return from the __len__ fallback method to designate falsec:\codec:\python \python class cdef __nonzero__(self)print('in nonzero'return false returns int (or true/falsesame as / (bool(xin nonzero false if xprint( in nonzero but keep in mind that __nonzero__ works in onlyif used in it will be silently ignored and the object will be classified as true by default--just like using ' __bool__ in xand now that we've managed to cross over into the realm of philosophylet' move on to look at one last overloading contextobject demise object destruction__del__ it' time to close out this -and learn how to do the same for our class objects we've seen how the __init__ constructor is called whenever an instance is generated (and noted how __new__ is run first to make the objectits counterpartthe destructor method __del__is run automatically when an instance' space is being reclaimed ( at "garbage collectiontime)class lifedef __init__(selfname='unknown')print('hello nameself name name def live(self)print(self namedef __del__(self)print('goodbye self nameobject destruction__del__
1,488
hello brian brian live(brian brian 'lorettagoodbye brian herewhen brian is assigned stringwe lose the last reference to the life instance and so trigger its destructor method this worksand it may be useful for implementing some cleanup activitiessuch as terminating server connection howeverdestructors are not as commonly used in python as in some oop languagesfor number of reasons that the next section describes destructor usage notes the destructor method works as documentedbut it has some well-known caveats and few outright dark corners that make it somewhat rare to see in python codeneedfor one thingdestructors may not be as useful in python as they are in some other oop languages because python automatically reclaims all memory space held by an instance when the instance is reclaimeddestructors are not necessary for space management in the current cpython implementation of pythonyou also don' need to close file objects held by the instance in destructors because they are automatically closed when reclaimed as mentioned in thoughit' still sometimes best to run file close methods anyhowbecause this autoclose behavior may vary in alternative python implementations ( jythonpredictabilityfor anotheryou cannot always easily predict when an instance will be reclaimed in some casesthere may be lingering references to your objects in system tables that prevent destructors from running when your program expects them to be triggered python also does not guarantee that destructor methods will be called for objects that still exist when the interpreter exits exceptionsin fact__del__ can be tricky to use for even more subtle reasons exceptions raised within itfor examplesimply print warning message to sys stderr (the standard error streamrather than triggering an exception eventbecause of the unpredictable context under which it is run by the garbage collector --it' not always possible to know where such an exception should be delivered cyclesin additioncyclic ( circularreferences among objects may prevent garbage collection from happening when you expect it to an optional cycle detectorenabled by defaultcan automatically collect such objects eventuallybut only if they do not have __del__ methods since this is relatively obscurewe'll ignore further details heresee python' standard manualscoverage of both __del__ and the gc garbage collector module for more information because of these downsidesit' often better to code termination activities in an explicitly called method ( shutdownas described in the next part of the bookthe operator overloading
1,489
for objects that support its context manager model summary that' as many overloading examples as we have space for here most of the other operator overloading methods work similarly to the ones we've exploredand all are just hooks for intercepting built-in type operations some overloading methodsfor examplehave unique argument lists or return valuesbut the general usage pattern is the same we'll see few others in action later in the book uses __enter__ and __exit__ in with statement context managers uses the __get__ and __set__ class descriptor fetch/set methods uses the __new__ object creation method in the context of metaclasses in additionsome of the methods we've studied heresuch as __call__ and __str__will be employed by later examples in this book for complete coveragethoughi'll defer to other documentation sources--see python' standard language manual or reference books for details on additional overloading methods in the next we leave the realm of class mechanics behind to explore common design patterns--the ways that classes are commonly used and combined to optimize code reuse after thatwe'll survey handful of advanced topics and move on to exceptionsthe last core subject of this book before you read onthoughtake moment to work through the quiz below to review the concepts we've covered test your knowledgequiz what two operator overloading methods can you use to support iteration in your classes what two operator overloading methods handle printingand in what contexts how can you intercept slice operations in class how can you catch in-place addition in class when should you provide operator overloadingtest your knowledgeanswers classes can support iteration by defining (or inheriting__getitem__ or __iter__ in all iteration contextspython tries to use __iter__ firstwhich returns an object that supports the iteration protocol with __next__ methodif no __iter__ is found by inheritance searchpython falls back on the __getitem__ indexing methodtest your knowledgeanswers
1,490
statement can create the __next__ method automatically the __str__ and __repr__ methods implement object print displays the former is called by the print and str built-in functionsthe latter is called by print and str if there is no __str__and always by the repr built-ininteractive echoesand nested appearances that is__repr__ is used everywhereexcept by print and str when __str__ is defined __str__ is usually used for user-friendly displays__repr__ gives extra details or the object' as-code form slicing is caught by the __getitem__ indexing methodit is called with slice objectinstead of simple integer indexand slice objects may be passed on or inspected as needed in python x__getslice__ (defunct in xmay be used for two-limit slices as well in-place addition tries __iadd__ firstand __add__ with an assignment second the same pattern holds true for all binary operators the __radd__ method is also available for right-side addition when class naturally matchesor needs to emulatea built-in type' interfaces for examplecollections might imitate sequence or mapping interfacesand callables might be coded for use with an api that expects function you generally shouldn' implement expression operators if they don' naturally map to your objects naturally and logicallythough--use normally named methods instead operator overloading
1,491
designing with classes so far in this part of the bookwe've concentrated on using python' oop toolthe class but oop is also about design issues--that ishow to use classes to model useful objects this will touch on few core oop ideas and present some additional examples that are more realistic than many shown so far along the waywe'll code some common oop design patterns in pythonsuch as inheritancecompositiondelegationand factories we'll also investigate some designfocused class conceptssuch as pseudoprivate attributesmultiple inheritanceand bound methods one note up frontsome of the design terms mentioned here require more explanation than can provide in this book if this material sparks your curiosityi suggest exploring text on oop design or design patterns as next step as we'll seethe good news is that python makes many traditional design patterns trivial python and oop let' begin with review--python' implementation of oop can be summarized by three ideasinheritance inheritance is based on attribute lookup in python (in name expressionspolymorphism in methodthe meaning of method depends on the type (classof subject object encapsulation methods and operators implement behaviorthough data hiding is convention by default by nowyou should have good feel for what inheritance is all about in python we've also talked about python' polymorphism few times alreadyit flows from python' lack of type declarations because attributes are always resolved at runtimeobjects that
1,492
know what sorts of objects are implementing the methods they call encapsulation means packaging in python--that ishiding implementation details behind an object' interface it does not mean enforced privacythough that can be implemented with codeas we'll see in encapsulation is available and useful in python nonethelessit allows the implementation of an object' interface to be changed without impacting the users of that object polymorphism means interfacesnot call signatures some oop languages also define polymorphism to mean overloading functions based on the type signatures of their arguments--the number passed and/or their types because there are no type declarations in pythonthis concept doesn' really applyas we've seenpolymorphism in python is based on object interfacesnot types if you're pining for your +daysyou can try to overload methods by their argument listslike thisclass cdef meth(selfx)def meth(selfxyz)this code will runbut because the def simply assigns an object to name in the class' scopethe last definition of the method function is the only one that will be retained put another wayit' just as if you say and then will be hencethere can be only one definition of method name if they are truly requiredyou can always code type-based selections using the typetesting ideas we met in and or the argument list tools introduced in class cdef meth(self*args)if len(args= elif type(arg[ ]=intbranch on number arguments branch on argument types (or isinstance()you normally shouldn' do thisthough--it' not the python way as described in you should write your code to expect only an object interfacenot specific data type that wayit will be useful for broader category of types and applicationsboth now and in the futureclass cdef meth(selfx) operation( designing with classes assume does the right thing
1,493
although python' object model is straightforwardmuch of the art in oop is in the way we combine classes to achieve program' goals the next section begins tour of some of the ways larger programs use classes to their advantage oop and inheritance"is-arelationships we've explored the mechanics of inheritance in depth alreadybut ' now like to show you an example of how it can be used to model real-world relationships from programmer' point of viewinheritance is kicked off by attribute qualificationswhich trigger searches for names in instancestheir classesand then any superclasses from designer' point of viewinheritance is way to specify set membershipa class defines set of properties that may be inherited and customized by more specific sets ( subclassesto illustratelet' put that pizza-making robot we talked about at the start of this part of the book to work suppose we've decided to explore alternative career paths and open pizza restaurant (not badas career paths goone of the first things we'll need to do is hire employees to serve customersprepare the foodand so on being engineers at heartwe've decided to build robot to make the pizzasbut being politically and cybernetically correctwe've also decided to make our robot full-fledged employee with salary our pizza shop team can be defined by the four classes in the following python and example fileemployees py the most general classemployeeprovides common behavior such as bumping up salaries (giveraiseand printing (__repr__there are two kinds of employeesand so two subclasses of employee--chef and server both override the inherited work method to print more specific messages finallyour pizza robot is modeled by an even more specific class--pizzarobot is kind of chefwhich is kind of employee in oop termswe call these relationships "is-alinksa robot is chefwhich is an employee here' the employees py filefile employees py ( xfrom __future__ import print_function class employeedef __init__(selfnamesalary= )self name name self salary salary def giveraise(selfpercent)self salary self salary (self salary percentdef work(self)print(self name"does stuff"def __repr__(self)return "(self nameself salaryclass chef(employee)oop and inheritance"is-arelationships
1,494
employee __init__(selfname def work(self)print(self name"makes food"class server(employee)def __init__(selfname)employee __init__(selfname def work(self)print(self name"interfaces with customer"class pizzarobot(chef)def __init__(selfname)chef __init__(selfnamedef work(self)print(self name"makes pizza"if __name__ ="__main__"bob pizzarobot('bob'print(bobbob work(bob giveraise( print(bob)print(make robot named bob run inherited __repr__ run type-specific action give bob raise for klass in employeechefserverpizzarobotobj klass(klass __name__obj work(when we run the self-test code included in this modulewe create pizza-making robot named bobwhich inherits names from three classespizzarobotchefand employee for instanceprinting bob runs the employee __repr__ methodand giving bob raise invokes employee giveraise because that' where the inheritance search finds that methodc:\codepython employees py bob makes pizza employee does stuff chef makes food server interfaces with customer pizzarobot makes pizza in class hierarchy like thisyou can usually make instances of any of the classesnot just the ones at the bottom for instancethe for loop in this module' self-test code creates instances of all four classeseach responds differently when asked to work because the work method is different in each bob the robotfor examplegets work from the most specific ( lowestpizzarobot class of coursethese classes just simulate real-world objectswork prints message for the time beingbut it could be expanded to do real work later (see python' interfaces to designing with classes
1,495
section much too literally!oop and composition"has-arelationships the notion of composition was introduced in and from programmer' point of viewcomposition involves embedding other objects in container objectand activating them to implement container methods to designercomposition is another way to represent relationships in problem domain butrather than set membershipcomposition has to do with components--parts of whole composition also reflects the relationships between partscalled "has-arelationships some oop design texts refer to composition as aggregationor distinguish between the two terms by using aggregation to describe weaker dependency between container and contained in this texta "compositionsimply refers to collection of embedded objects the composite class generally provides an interface all its own and implements it by directing the embedded objects now that we've implemented our employeeslet' put them in the pizza shop and let them get busy our pizza shop is composite objectit has an ovenand it has employees like servers and chefs when customer enters and places an orderthe components of the shop spring into action--the server takes the orderthe chef makes the pizzaand so on the following example--file pizzashop py--runs the same on python and and simulates all the objects and relationships in this scenariofile pizzashop py ( xfrom __future__ import print_function from employees import pizzarobotserver class customerdef __init__(selfname)self name name def order(selfserver)print(self name"orders from"serverdef pay(selfserver)print(self name"pays for item to"serverclass ovendef bake(self)print("oven bakes"class pizzashopdef __init__(self)self server server('pat'self chef pizzarobot('bob'self oven oven(def order(selfname)customer customer(namecustomer order(self serverembed other objects robot named bob activate other objects customer orders from server oop and composition"has-arelationships
1,496
self oven bake(customer pay(self serverif __name__ ="__main__"scene pizzashop(scene order('homer'print('scene order('shaggy'make the composite simulate homer' order simulate shaggy' order the pizzashop class is container and controllerits constructor makes and embeds instances of the employee classes we wrote in the prior sectionas well as an oven class defined here when this module' self-test code calls the pizzashop order methodthe embedded objects are asked to carry out their actions in turn notice that we make new customer object for each orderand we pass on the embedded server object to customer methodscustomers come and gobut the server is part of the pizza shop composite also notice that employees are still involved in an inheritance relationshipcomposition and inheritance are complementary tools when we run this moduleour pizza shop handles two orders--one from homerand then one from shaggyc:\codepython pizzashop py homer orders from bob makes pizza oven bakes homer pays for item to shaggy orders from bob makes pizza oven bakes shaggy pays for item to againthis is mostly just toy simulationbut the objects and interactions are representative of composites at work as rule of thumbclasses can represent just about any objects and relationships you can express in sentencejust replace nouns with classes ( oven)and verbs with methods ( bake)and you'll have first cut at design stream processors revisited for composition example that may be bit more tangible than pizza-making robotsrecall the generic data stream processor function we partially coded in the introduction to oop in def processor(readerconverterwriter)while truedata reader read(if not databreak data converter(datawriter write(data designing with classes
1,497
following / filestreams pydemonstrates one way to code the classclass processordef __init__(selfreaderwriter)self reader reader self writer writer def process(self)while truedata self reader readline(if not databreak data self converter(dataself writer write(datadef converter(selfdata)assert false'converter must be definedor raise exception this class defines converter method that it expects subclasses to fill init' an example of the abstract superclass model we outlined in (more on assert in part vii-it simply raises an exception if its test is falsecoded this wayreader and writer objects are embedded within the class instance (composition)and we supply the conversion logic in subclass rather than passing in converter function (inheritancethe file converters py shows howfrom streams import processor class uppercase(processor)def converter(selfdata)return data upper(if __name__ ='__main__'import sys obj uppercase(open('trispam txt')sys stdoutobj process(herethe uppercase class inherits the stream-processing loop logic (and anything else that may be coded in its superclassesit needs to define only what is unique about it --the data conversion logic when this file is runit makes and runs an instance that reads from the file trispam txt and writes the uppercase equivalent of that file to the stdout streamc:\codetype trispam txt spam spam spamc:\codepython converters py spam spam spamoop and composition"has-arelationships
1,498
:\codepython import converters prog converters uppercase(open('trispam txt')open('trispamup txt'' ')prog process( :\codetype trispamup txt spam spam spambutas suggested earlierwe could also pass in arbitrary objects coded as classes that define the required input and output method interfaces here' simple example that passes in writer class that wraps up the text inside html tagsc:\codepython from converters import uppercase class htmlizedef write(selfline)print('%sline rstrip()uppercase(open('trispam txt')htmlize()process(spam spam spamif you trace through this example' control flowyou'll see that we get both uppercase conversion (by inheritanceand html formatting (by composition)even though the core processing logic in the original processor superclass knows nothing about either step the processing code only cares that writers have write method and that method named convert is definedit doesn' care what those methods do when they are called such polymorphism and encapsulation of logic is behind much of the power of classes in python as isthe processor superclass only provides file-scanning loop in more realistic workwe might extend it to support additional programming tools for its subclassesandin the processturn it into full-blown application framework coding such tool once in superclass enables you to reuse it in all of your programs even in this simple examplebecause so much is packaged and inherited with classesall we had to code was the html formatting stepthe rest was free for another example of composition at worksee exercise at the end of and its solution in appendix dit' similar to the pizza shop example we've focused on inheritance in this book because that is the main tool that the python language itself provides for oop butin practicecomposition may be used as much as inheritance as way to structure classesespecially in larger systems as we've seeninheritance and composition are often complementary (and sometimes alternativetechniques designing with classes
1,499
this bookthoughi'll defer to other resources for more on this topic why you will careclasses and persistence 've mentioned python' pickle and shelve object persistence support few times in this part of the book because it works especially well with class instances in factthese tools are often compelling enough to motivate the use of classes in general--by pickling or shelving class instancewe get data storage that contains both data and logic combined for examplebesides allowing us to simulate real-world interactionsthe pizza shop classes developed in this could also be used as the basis of persistent restaurant database instances of classes can be stored away on disk in single step using python' pickle or shelve modules we used shelves to store instances of classes in the oop tutorial in but the object pickling interface is remarkably easy to use as wellimport pickle object someclass(file open(filename'wb'pickle dump(objectfilecreate external file save object in file import pickle file open(filename'rb'object pickle load(filefetch it back later pickling converts in-memory objects to serialized byte streams (in pythonstrings)which may be stored in filessent across networkand so onunpickling converts back from byte streams to identical in-memory objects shelves are similarbut they automatically pickle objects to an access-by-key databasewhich exports dictionarylike interfaceimport shelve object someclass(dbase shelve open(filenamedbase['key'object save under key import shelve dbase shelve open(filenameobject dbase['key'fetch it back later in our pizza shop exampleusing classes to model employees means we can get simple database of employees and shops with little extra work--pickling such instance objects to file makes them persistent across python program executionsfrom pizzashop import pizzashop shop pizzashop(shop servershop chef (import pickle pickle dump(shopopen('shopfile pkl''wb')this stores an entire composite shop object in file all at once to bring it back later in another session or programa single step suffices as well in factobjects restored this way retain both state and behavioroop and composition"has-arelationships