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 obj... |
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 m... |
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--... |
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 modul... |
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)lis... |
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 id... |
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(se... |
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 n... |
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... |
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 ou... |
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... |
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 jones... |
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 sh... |
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... |
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 sil... |
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 simp... |
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 classe... |
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 dire... |
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 inheritanc... |
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 f... |
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... |
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 ... |
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 a... |
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 print... |
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 ca... |
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... |
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 ... |
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 d... |
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 callp... |
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 t... |
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... |
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 name... |
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... |
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 sens... |
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... |
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... |
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 global... |
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 o... |
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 automati... |
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 th... |
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 ... |
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"mi... |
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__ discuss... |
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 ... |
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 t... |
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 met... |
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 numb... |
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... |
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 ot... |
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 ... |
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 slic... |
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 cal... |
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)retu... |
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... |
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 des... |
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 th... |
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 square... |
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 d... |
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 skipite... |
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 ... |
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 automaticall... |
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 ... |
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 thi... |
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 squaresiterd... |
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 l... |
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 contex... |
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 impl... |
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 ... |
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__(... |
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 th... |
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 __getatt... |
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 emulat... |
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... |
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 addin... |
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' stri... |
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 p... |
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 +a... |
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... |
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 ... |
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 quic... |
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 p... |
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--... |
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 functi... |
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 ... |
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__(s... |
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 i... |
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(bo... |
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... |
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 common... |
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 ... |
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_... |
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 alo... |
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 nonetheless... |
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 alr... |
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__ ="__ma... |
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 relationsh... |
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 pr... |
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 def... |
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 p... |
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 motiv... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.