id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
1,500 | obj pickle load(open('shopfile pkl''rb')obj serverobj chef (obj order('lsp'lsp orders from bob makes pizza oven bakes lsp pays for item to this just runs simulation as isbut we might extend the shop to keep track of inventoryrevenueand so on--saving it to its file after changes would retain its updated state see the standard library manual and related coverage in and for more on pickles and shelves oop and delegation"wrapperproxy objects beside inheritance and compositionobject-oriented programmers often speak of delegationwhich usually implies controller objects that embed other objects to which they pass off operation requests the controllers can take care of administrative activitiessuch as logging or validating accessesadding extra steps to interface componentsor monitoring active instances in sensedelegation is special form of compositionwith single embedded object managed by wrapper (sometimes called proxyclass that retains most or all of the embedded object' interface the notion of proxies sometimes applies to other mechanisms toosuch as function callsin delegationwe're concerned with proxies for all of an object' behaviorincluding method calls and other operations this concept was introduced by example in and in python is often implemented with the __getattr__ method hook we studied in because this operator overloading method intercepts accesses to nonexistent attributesa wrapper class can use __getattr__ to route arbitrary accesses to wrapped object because this method allows attribute requests to be routed genericallythe wrapper class retains the interface of the wrapped object and may add additional operations of its own by way of reviewconsider the file trace py (which runs the same in and )class wrapperdef __init__(selfobject)self wrapped object def __getattr__(selfattrname)print('traceattrnamereturn getattr(self wrappedattrnamesave object trace fetch delegate fetch recall from that __getattr__ gets the attribute name as string this code makes use of the getattr built-in function to fetch an attribute from the wrapped object by name string--getattr( ,nis like nexcept that is an expression that evaluates to string at runtimenot variable in factgetattr( ,nis similar to __dict__[ ] designing with classes |
1,501 | (see and for more on the __dict__ attributeyou can use the approach of this module' wrapper class to manage access to any object with attributes--listsdictionariesand even classes and instances herethe wrapper class simply prints trace message on each attribute access and delegates the attribute request to the embedded wrapped objectfrom trace import wrapper wrapper([ ] append( traceappend wrapped [ wrapper({' ' ' ' }list( keys()tracekeys [' '' 'wrap list delegate to list method print my member wrap dictionary delegate to dictionary method the net effect is to augment the entire interface of the wrapped objectwith additional code in the wrapper class we can use this to log our method callsroute method calls to extra or custom logicadapt class to new interfaceand so on we'll revive the notions of wrapped objects and delegated operations as one way to extend built-in types in the next if you are interested in the delegation design patternalso watch for the discussions in and of function decoratorsa strongly related concept designed to augment specific function or method call rather than the entire interface of an objectand class decoratorswhich serve as way to automatically add such delegation-based wrappers to all instances of class version skew noteas we saw by example in delegation of object interfaces by general proxies has changed substantially in when wrapped objects implement operator overloading methods technicallythis is new-style class differenceand can appear in code too if it enables this optionper the next it' mandatory in and thus often considered change in python ' default classesoperator overloading methods run by built-in operations are routed through generic attribute interception methods like __getattr__ printing wrapped object directlyfor examplecalls this method for __repr__ or __str__which then passes the call on to the wrapped object this pattern holds for __iter____add__and the other operator methods of the prior in python xthis no longer happensprinting does not trigger __get attr__ (or its __getattribute__ cousin we'll study in the next and default display is used instead in xnew-style classes look up methods invoked implicitly by built-in operations in classes and skip the normal instance lookup entirely explicit name attribute fetches are routed to __getattr__ the same way in both and xbut built-in oop and delegation"wrapperproxy objects |
1,502 | we'll return to this issue in the next as new-style class changeand see it live in and in the context of managed attributes and decorators for nowkeep in mind that for delegation coding patternsyou may need to redefine operator overloading methods in wrapper classes (either by handby toolsor by superclassesif they are used by embedded objects and you want them to be intercepted in new-style classes pseudoprivate class attributes besides larger structuring goalsclass designs often must address name usage too in ' case studyfor examplewe noted that methods defined within general tool class might be modified by subclasses if exposedand noted the tradeoffs of this policy--while it supports method customization and direct callsit' also open to accidental replacements in part vwe learned that every name assigned at the top level of module file is exported by defaultthe same holds for classes--data hiding is conventionand clients may fetch or change attributes in any class or instance to which they have reference in factattributes are all "publicand "virtual,in +termsthey're all accessible everywhere and are looked up dynamically at runtime that saidpython today does support the notion of name "mangling( expansionto localize some names in classes mangled names are sometimes misleadingly called "private attributes,but really this is just way to localize name to the class that created it--name mangling does not prevent access by code outside the class this feature is mostly intended to avoid namespace collisions in instancesnot to restrict access to names in generalmangled names are therefore better called "pseudoprivatethan "private pseudoprivate names are an advanced and entirely optional featureand you probably won' find them very useful until you start writing general tools or larger class hierarchies for use in multiprogrammer projects in factthey are not always used even when they probably should be--more commonlypython programmers code internal names with single underscore ( _x)which is just an informal convention to let you know that name shouldn' generally be changed (it means nothing to python itself this tends to scare people with +background disproportionately in pythonit' even possible to change or completely delete class' method at runtime on the other handalmost nobody ever does this in practical programs as scripting languagepython is more about enabling than restricting alsorecall from our discussion of operator overloading in that __getattr__ and __setattr__ can be used to emulate privacybut are generally not used for this purpose in practice more on this when we code more realistic privacy decorator in designing with classes |
1,503 | and contexts of useyou may find this feature to be more useful in your own code than some programmers realize name mangling overview here' how name mangling workswithin class statement onlyany names that start with two underscores but don' end with two underscores are automatically expanded to include the name of the enclosing class at their front for instancea name like __x within class named spam is changed to _spam__x automaticallythe original name is prefixed with single underscore and the enclosing class' name because the modified name contains the name of the enclosing classit' generally uniqueit won' clash with similar names created by other classes in hierarchy name mangling happens only for names that appear inside class statement' codeand then only for names that begin with two leading underscores it works for every name preceded with double underscoresthough--both class attributes (including method namesand instance attribute names assigned to self for examplein class named spama method named __meth is mangled to _spam__methand an instance attribute reference self __x is transformed to self _spam__x despite the manglingas long as the class uses the double underscore version everywhere it refers to the nameall its references will still work because more than one class may add attributes to an instancethoughthis mangling helps avoid clashes--but we need to move on to an example to see how why use pseudoprivate attributesone of the main issues that the pseudoprivate attribute feature is meant to alleviate has to do with the way instance attributes are stored in pythonall instance attributes wind up in the single instance object at the bottom of the class treeand are shared by all class-level method functions the instance is passed into this is different from the +modelwhere each class gets its own space for data members it defines within class' method in pythonwhenever method assigns to self attribute ( self attr value)it changes or creates an attribute in the instance (recall that inheritance searches happen only on referencenot on assignmentbecause this is true even if multiple classes in hierarchy assign to the same attributecollisions are possible for examplesuppose that when programmer codes classit is assumed that the class owns the attribute name in the instance in this class' methodsthe name is setand later fetchedclass def meth (self)self def meth (self)print(self xi assume is mine pseudoprivate class attributes |
1,504 | class def metha(self)self def methb(self)print(self xme too both of these classes work by themselves the problem arises if the two classes are ever mixed together in the same class treeclass ( ) (only in inowthe value that each class gets back when it says self will depend on which class assigned it last because all assignments to self refer to the same single instancethere is only one attribute-- --no matter how many classes use that attribute name this isn' problem if it' expectedand indeedthis is how classes communicate--the instance is shared memory to guarantee that an attribute belongs to the class that uses itthoughprefix the name with double underscores everywhere it is used in the classas in this / filepseudoprivate pyclass def meth (self)self __x def meth (self)print(self __xclass def metha(self)self __x def methb(self)print(self __xclass ( )pass (now is mine becomes _c __x in me too becomes _c __x in two names in meth () metha(print( __dict__i meth () methb(when thus prefixedthe attributes will be expanded to include the names of their classes before being added to the instance if you run dir call on or inspect its namespace dictionary after the attributes have been assignedyou'll see the expanded names_c __x and _c __xbut not because the expansion makes the names more unique within the instancethe class coders can be fairly safe in assuming that they truly own any names that they prefix with two underscorespython pseudoprivate py {'_c __x' '_c __x' this trick can avoid potential name collisions in the instancebut note that it does not amount to true privacy if you know the name of the enclosing classyou can still access either of these attributes anywhere you have reference to the instance by using the fully expanded name ( _c __x moreovernames could still collide if unknowing programmers use the expanded naming pattern explicitly (unlikelybut not designing with classes |
1,505 | pseudoprivate attributes are also useful in larger frameworks or toolsboth to avoid introducing new method names that might accidentally hide definitions elsewhere in the class tree and to reduce the chance of internal methods being replaced by names defined lower in the tree if method is intended for use only within class that may be mixed into other classesthe double underscore prefix virtually ensures that the method won' interfere with other names in the treeespecially in multiple-inheritance scenariosclass superdef method(self) real application method class tooldef __method(self)def other(self)self __method(becomes _tool__method use my internal method class sub (toolsuper)def actions(self)self method(runs super method as expected class sub (tool)def __init__(self)self method doesn' break tool __method we met multiple inheritance briefly in and will explore it in more detail later in this recall that superclasses are searched according to their left-to-right order in class header lines herethis means sub prefers tool attributes to those in super although in this example we could force python to pick the application class' methods first by switching the order of the superclasses listed in the sub class headerpseudoprivate attributes resolve the issue altogether pseudoprivate names also prevent subclasses from accidentally redefining the internal method' namesas in sub againi should note that this feature tends to be of use primarily for largermultiprogrammer projectsand then only for selected names don' be tempted to clutter your code unnecessarilyonly use this feature for names that truly need to be controlled by single class although useful in some general class-based toolsfor simpler programsit' probably overkill for more examples that make use of the __x naming featuresee the lister py mix-in classes introduced later in this in the multiple inheritance sectionas well as the discussion of private class decorators in if you care about privacy in generalyou might want to review the emulation of private instance attributes sketched in the section "attribute access__getattr__ and __setattr__on page in and watch for the more complete private class decorator we'll build with delegation in although it' possible to emulate true access controls in python classesthis is rarely done in practiceeven for large systems pseudoprivate class attributes |
1,506 | methods in generaland bound methods in particularsimplify the implementation of many design goals in python we met bound methods briefly while studying __call__ in the full storywhich we'll flesh out hereturns out to be more general and flexible than you might expect in we learned how functions can be processed as normal objects methods are kind of object tooand can be used generically in much the same way as other objects--they can be assigned to namespassed to functionsstored in data structuresand so on--and like simple functionsqualify as "first classobjects because class' methods can be accessed from an instance or classthoughthey actually come in two flavors in pythonunbound (classmethod objectsno self accessing function attribute of class by qualifying the class returns an unbound method object to call the methodyou must provide an instance object explicitly as the first argument in python xan unbound method is the same as simple function and can be called through the class' namein it' distinct type and cannot be called without providing an instance bound (instancemethod objectsself function pairs accessing function attribute of class by qualifying an instance returns bound method object python automatically packages the instance with the function in the bound method objectso you don' need to pass an instance to call the method both kinds of methods are full-fledged objectsthey can be transferred around program at willjust like strings and numbers both also require an instance in their first argument when run ( value for selfthis is why we've had to pass in an instance explicitly when calling superclass methods from subclass methods in previous examples (including this employees py)technicallysuch calls produce unbound method objects along the way when calling bound method objectpython provides an instance for you automatically--the instance used to create the bound method object this means that bound method objects are usually interchangeable with simple function objectsand makes them especially useful for interfaces originally written for functions (see the sidebar "why you will carebound method callbackson page for realistic use case in guisto illustrate in simple termssuppose we define the following classclass spamdef doit(selfmessage)print(messagenowin normal operationwe make an instance and call its method in single step to print the passed-in argument designing with classes |
1,507 | object doit('hello world'reallythougha bound method object is generated along the wayjust before the method call' parentheses in factwe can fetch bound method without actually calling it an object name expression evaluates to an object as all expressions do in the followingit returns bound method object that packages the instance (object with the method function (spam doitwe can assign this bound method pair to another name and then call it as though it were simple functionobject spam( object doit ('hello world'bound method objectinstance+function same effect as object doit('on the other handif we qualify the class to get to doitwe get back an unbound method objectwhich is simply reference to the function object to call this type of methodwe must pass in an instance as the leftmost argument--there isn' one in the expression otherwiseand the method expects itobject spam( spam doit (object 'howdy'unbound method object ( function in xsee aheadpass in instance (if the method expects one in xby extensionthe same rules apply within class' method if we reference self attributes that refer to functions in the class self method expression is bound method object because self is an instance objectclass eggsdef (selfn)print(ndef (self) self ( another bound method object looks like simple function eggs( (prints most of the timeyou call methods immediately after fetching them with attribute qualificationso you don' always notice the method objects generated along the way but if you start writing code that calls objects genericallyyou need to be careful to treat unbound methods specially--they normally require an explicit instance object to be passed in for an optional exception to this rulesee the discussion of static and class methods in the next and the brief mention of one in the next section like bound methodsstatic methods can masquerade as basic functions because they do not expect instances when called formally speakingpython supports three kinds of class-level methods-instancestaticand class--and allows simple functions in classestoo ' metaclass methods are distinct toobut they are essentially class methods with less scope methods are objectsbound or unbound |
1,508 | in python xthe language has dropped the notion of unbound methods what we describe as an unbound method here is treated as simple function in for most purposesthis makes no difference to your codeeither wayan instance will be passed to method' first argument when it' called through an instance programs that do explicit type testing might be impactedthough--if you print the type of an instance-less class-level methodit displays "unbound methodin xand "functionin moreoverin it is ok to call method without an instanceas long as the method does not expect one and you call it only through the class and never through an instance that ispython will pass along an instance to methods only for through-instance calls when calling through classyou must pass an instance manually only if the method expects onec:\codec:\python \python class selflessdef __init__(selfdata)self data data def selfless(arg arg )return arg arg def normal(selfarg arg )return self data arg arg selfless( normal( selfless normal( selfless selfless( simple function in instance expected when called instance passed to self automatically +( + self expected by methodpass manually no instanceworks in xfails in xthe last test in this fails in xbecause unbound methods require an instance to be passed by defaultit works in because such methods are treated as simple functions not requiring an instance although this removes some potential error trapping in (what if programmer accidentally forgets to pass an instance?)it allows class' methods to be used as simple functions as long as they are not passed and do not expect "selfinstance argument the following two calls still fail in both and xthough--the first (calling through an instanceautomatically passes an instance to method that does not expect onewhile the second (calling through classdoes not pass an instance to method that does expect one (error message text here is per ) selfless( typeerrorselfless(takes positional arguments but were given selfless normal( typeerrornormal(missing required positional argument'arg designing with classes |
1,509 | the next is not needed in for methods without self argument that are called only through the class nameand never through an instance--such methods are run as simple functionswithout receiving an instance argument in xsuch calls are errors unless an instance is passed manually or the method is marked as being static (more on static methods in the next it' important to be aware of the differences in behavior in xbut bound methods are generally more important from practical perspective anyway because they pair together the instance and function in single objectthey can be treated as callables generically the next section demonstrates what this means in code for more visual illustration of unbound method treatment in python and xsee also the lister py example in the multiple inheritance section later in this its classes print the value of methods fetched from both instances and classesin both versions of python--as unbound methods in and simple functions in also note that this change is inherent in itselfnot the new-style class model it mandates bound methods and other callable objects as mentioned earlierbound methods can be processed as generic objectsjust like simple functions--they can be passed around program arbitrarily moreoverbecause bound methods combine both function and an instance in single packagethey can be treated like any other callable object and require no special syntax when invoked the followingfor examplestores four bound method objects in list and calls them later with normal call expressionsclass numberdef __init__(selfbase)self base base def double(self)return self base def triple(self)return self base number( number( number( double( class instance objects state methods acts [ doubley doubley triplez doublefor act in actsprint(act()list of bound methods calls are deferred call as though functions normal immediate calls methods are objectsbound or unbound |
1,510 | like simple functionsbound method objects have introspection information of their ownincluding attributes that give access to the instance object and method function they pair calling the bound method simply dispatches the pairbound double bound __self__bound __func__ (bound __self__ base bound(calls bound __func__(bound __self__ other callables in factbound methods are just one of handful of callable object types in python as the following demonstratessimple functions coded with def or lambdainstances that inherit __call__and bound instance methods can all be treated and called the same waydef square(arg)return arg * class sumdef __init__(selfval)self val val def __call__(selfarg)return self val arg class productdef __init__(selfval)self val val def method(selfarg)return self val arg simple functions (def or lambdacallable instances bound methods sobject sum( pobject product( actions [squaresobjectpobject methodfunctioninstancemethod for act in actionsprint(act( ) actions[- ]( [act( for act in actions[ list(map(lambda actact( )actions)[ designing with classes all three called same way call any one-arg callable indexcomprehensionsmaps |
1,511 | better coded as simple function than class with constructorbut the class here serves to illustrate its callable natureclass negatedef __init__(selfval)self val -val def __repr__(self)return str(self valclasses are callables too but called for objectnot work instance print format actions [squaresobjectpobject methodnegatefor act in actionsprint(act( ) - [act( for act in actions[ - table {act( )act for act in actionsfor (keyvaluein table items()print('{ : ={ }format(keyvalue)call class too runs __repr__ not __str__ / dict comprehension +/ str format = =- = =as you can seebound methodsand python' callable objects model in generalare some of the many ways that python' design makes for an incredibly flexible language you should now understand the method object model for other examples of bound methods at worksee the upcoming sidebar "why you will carebound method callbackson page as well as the prior discussion of callback handlers in the section on the method __call__ why you will carebound method callbacks because bound methods automatically pair an instance with class' method functionyou can use them anywhere simple function is expected one of the most common places you'll see this idea put to work is in code that registers methods as event callback handlers in the tkinter gui interface (named tkinter in python xwe've met before as reviewhere' the simple casedef handler()use globals or closure scopes for state widget button(text='spam'command=handlerto register handler for button click eventswe usually pass callable object that takes no arguments to the command keyword argument function names (and lambdaswork methods are objectsbound or unbound |
1,512 | class myguidef handler(self)use self attr for state def makewidgets(self) button(text='spam'command=self handlerherethe event handler is self handler-- bound method object that remembers both self and mygui handler because self will refer to the original instance when handler is later invoked on eventsthe method will have access to instance attributes that can retain state between eventsas well as class-level methods with simple functionsstate normally must be retained in global variables or enclosing function scopes instead see also the discussion of __call__ operator overloading in for another way to make classes compatible with function-based apisand lambda in for another tool often used in callback roles as noted in the former of theseyou don' generally need to wrap bound method in lambdathe bound method in the preceding example already defers the call (note that there are no parentheses to trigger one)so adding lambda here would be pointlessclasses are objectsgeneric object factories sometimesclass-based designs require objects to be created in response to conditions that can' be predicted when program is written the factory design pattern allows such deferred approach due in large part to python' flexibilityfactories can take multiple formssome of which don' seem special at all because classes are also "first classobjectsit' easy to pass them around programstore them in data structuresand so on you can also pass classes to functions that generate arbitrary kinds of objectssuch functions are sometimes called factories in oop design circles factories can be major undertaking in strongly typed language such as +but are almost trivial to implement in python for examplethe call syntax we met in can call any class with any number of positional or keyword constructor arguments in one step to generate any sort of instance: def factory(aclass*pargs**kargs)return aclass(*pargs**kargsvarargs tupledict call aclass (or apply in onlyclass spam actuallythis syntax can invoke any callable objectincluding functionsclassesand methods hencethe factory function here can also run any callable objectnot just class (despite the argument namealsoas we learned in python has an alternative to aclass(*pargs**kargs)the apply(aclasspargskargsbuilt-in callwhich has been removed in python because of its redundancy and limitations designing with classes |
1,513 | print(messageclass persondef __init__(selfnamejob=none)self name name self job job object factory(spammake spam object object factory(person"arthur""king"make person object object factory(personname='brian'dittowith keywords and default in this codewe define an object generator function called factory it expects to be passed class object (any class will doalong with one or more arguments for the class' constructor the function uses special "varargscall syntax to call the function and return an instance the rest of the example simply defines two classes and generates instances of both by passing them to the factory function and that' the only factory function you'll ever need to write in pythonit works for any class and any constructor arguments if you run this live (factory py)your objects will look like thisobject doit( object nameobject job ('arthur''king'object nameobject job ('brian'noneby nowyou should know that everything is "first classobject in python--including classeswhich are usually just compiler input in languages like +it' natural to pass them around this way as mentioned at the start of this part of the bookthoughonly objects derived from classes do full oop in python why factoriesso what good is the factory function (besides providing an excuse to illustrate firstclass class objects in this book)unfortunatelyit' difficult to show applications of this design pattern without listing much more code than we have space for here in generalthoughsuch factory might allow code to be insulated from the details of dynamically configured object construction for instancerecall the processor example presented in the abstract in and then again as composition example earlier in this it accepts reader and writer objects for processing arbitrary data streams the original version of this example manually passed in instances of specialized classes like filewriter and socketreader to customize the data streams being processedlaterwe passed in hardcoded filestreamand formatter objects in more dynamic scenarioexternal devices such as configuration files or guis might be used to configure the streams classes are objectsgeneric object factories |
1,514 | interface objects in our scriptsbut might instead create them at runtime according to the contents of configuration file such file might simply give the string name of stream class to be imported from moduleplus an optional constructor call argument factory-style functions or code might come in handy here because they would allow us to fetch and pass in classes that are not hardcoded in our program ahead of time indeedthose classes might not even have existed at all when we wrote our codeclassname parse from config file classarg parse from config file import streamtypes aclass getattr(streamtypesclassnamereader factory(aclassclassargprocessor(readercustomizable code fetch from module or aclass(classargherethe getattr built-in is again used to fetch module attribute given string name (it' like saying obj attrbut attr is stringbecause this code snippet assumes single constructor argumentit doesn' strictly need factory--we could make an instance with just aclass(classargthe factory function may prove more useful in the presence of unknown argument listshoweverand the general factory coding pattern can improve the code' flexibility multiple inheritance"mix-inclasses our last design pattern is one of the most usefuland will serve as subject for more realistic example to wrap up this and point toward the next as bonusthe code we'll write here may be useful tool many class-based designs call for combining disparate sets of methods as we've seenin class statementmore than one superclass can be listed in parentheses in the header line when you do thisyou leverage multiple inheritance--the class and its instances inherit names from all the listed superclasses when searching for an attributepython' inheritance search traverses all superclasses in the class header from left to right until match is found technicallybecause any of the superclasses may have superclasses of its ownthis search can be bit more complex for larger class treesin classic classes (the default until python )the attribute search in all cases proceeds depth-first all the way to the top of the inheritance treeand then from left to right this order is usually called dflrfor its depth-firstleft-to-right path in new-style classes (optional in and standard in )the attribute search is usually as beforebut in diamond patterns proceeds across by tree levels before moving upin more breadth-first fashion this order is usually called the new designing with classes |
1,515 | methods the second of these search rules is explained fully in the new-style class discussion in the next though difficult to understand without the next code (and somewhat rare to create yourself)diamond patterns appear when multiple classes in tree share common superclassthe new-style search order is designed to visit such shared superclass just onceand after all its subclasses in either modelthoughwhen class has multiple superclassesthey are searched from left to right according to the order listed in the class statement header lines in generalmultiple inheritance is good for modeling objects that belong to more than one set for instancea person may be an engineera writera musicianand so onand inherit properties from all such sets with multiple inheritanceobjects obtain the union of the behavior in all their superclasses as we'll see aheadmultiple inheritance also allows classes to function as general packages of mixable attributes though useful patternmultiple inheritance' chief downside is that it can pose conflict when the same method (or other attributename is defined in more than one superclass when this occursthe conflict is resolved either automatically by the inheritance search orderor manually in your codedefaultby defaultinheritance chooses the first occurrence of an attribute it finds when an attribute is referenced normally--by self method()for example in this modepython chooses the lowest and leftmost in classic classesand in nondiamond patterns in all classesnew-style classes may choose an option to the right before one above in diamonds explicitin some class modelsyou may sometimes need to select an attribute explicitly by referencing it through its class name--with superclass method(self)for instance your code breaks the conflict and overrides the search' default--to select an option to the right of or above the inheritance search' default this is an issue only when the same name appears in multiple superclassesand you do not wish to use the first one inherited because this isn' as common an issue in typical python code as it may soundwe'll defer details on this topic until we study new-style classes and their mro and super tools in the next and revisit this as "gotchaat the end of that firstthoughthe next section demonstrates practical use case for multiple inheritance-based tools coding mix-in display classes perhaps the most common way multiple inheritance is used is to "mix ingeneralpurpose methods from superclasses such superclasses are usually called mix-in classes --they provide methods you add to application classes by inheritance in sensemixin classes are similar to modulesthey provide packages of methods for use in their client subclasses unlike simple functions in modulesthoughmethods in mix-in multiple inheritance"mix-inclasses |
1,516 | for exampleas we've seenpython' default way to print class instance object isn' incredibly usefulclass spamdef __init__(self)self data "foodx spam(print(xno __repr__ or __str__ defaultclass name address (idsame in xbut says "instanceas you saw in both ' case study and ' operator overloading coverageyou can provide __str__ or __repr__ method to implement custom string representation of your own butrather than coding one of these in each and every class you wish to printwhy not code it once in general-purpose tool class and inherit it in all your classesthat' what mix-ins are for defining display method in mix-in superclass once enables us to reuse it anywhere we want to see custom display format--even in classes that may already have another superclass we've already seen tools that do related work' attrdisplay class formatted instance attributes in generic __repr__ methodbut it did not climb class trees and was utilized in single-inheritance mode only ' classtree py module defined functions for climbing and sketching class treesbut it did not display object attributes along the way and was not architected as an inheritable class herewe're going to revisit these examplestechniques and expand upon them to code set of three mix-in classes that serve as generic display tools for listing instance attributesinherited attributesand attributes on all objects in class tree we'll also use our tools in multiple-inheritance mode and deploy coding techniques that make classes better suited to use as generic tools unlike we'll also code this with __str__ instead of __repr__ this is partially style issue and limits their role to print and strbut the displays we'll be developing will be rich enough to be categorized as more user-friendly than as-code this policy also leaves client classes the option of coding an alternative lower-level display for interactive echoes and nested appearances with __repr__ using __repr__ here would still allow an alternative __str__but the nature of the displays we'll be implementing more strongly suggests __str__ role see for review of these distinctions designing with classes |
1,517 | let' get started with the simple case--listing attributes attached to an instance the following classcoded in the file listinstance pydefines mix-in called listinstance that overloads the __str__ method for all classes that include it in their header lines because this is coded as classlistinstance is generic tool whose formatting logic can be used for instances of any subclass client#!python file listinstance py ( xclass listinstance""mix-in class that provides formatted print(or str(of instances via inheritance of __str__ coded heredisplays instance attrs onlyself is instance of lowest class__x names avoid clashing with client' attrs ""def __attrnames(self)result 'for attr in sorted(self __dict__)result +'\ % =% \ (attrself __dict__[attr]return result def __str__(self)return 'self __class__ __name__id(self)self __attrnames()my class' name my address name=value list if __name__ ='__main__'import testmixin testmixin tester(listinstanceall the code in this section runs in both python and coding notethis code exhibits classic comprehension patternand you could save some program real estate by implementing the __attrnames method here more concisely with generator expression that is triggered by the string join methodbut it' arguably less clear--expressions that wrap lines like this should generally make you consider simpler coding alternativesdef __attrnames(self)return 'join('\ % =% \ (attrself __dict__ [attr]for attr in sorted(self __dict__)listinstance uses some previously explored tricks to extract the instance' class name and attributeseach instance has built-in __class__ attribute that references the class from which it was createdand each class has __name__ attribute that references the name in the headerso the expression self __class__ __name__ fetches the name of an instance' class multiple inheritance"mix-inclasses |
1,518 | names and values of all instance attributes the dictionary' keys are sorted to finesse any ordering differences across python releases in these respectslistinstance is similar to ' attribute displayin factit' largely just variation on theme our class here uses two additional techniquesthoughit displays the instance' memory address by calling the id built-functionwhich returns any object' address (by definitiona unique object identifierwhich will be useful in later mutations of this codeit uses the pseudoprivate naming pattern for its worker method__attrnames as we learned earlier in this python automatically localizes any such name to its enclosing class by expanding the attribute name to include the class name (in this caseit becomes _listinstance__attrnamesthis holds true for both class attributes (like methodsand instance attributes attached to self as noted in ' first-cut versionthis behavior is useful in general tool like thisas it ensures that its names don' clash with any names used in its client subclasses because listinstance defines __str__ operator overloading methodinstances derived from this class display their attributes automatically when printedgiving bit more information than simple address here is the class in actionin single-inheritance modemixed in to the previous section' class (this code works the same in both python and xthough default repr displays use the label "instanceinstead of "object")from listinstance import listinstance class spam(listinstance)def __init__(self)self data 'foodx spam(print( <instance of spamaddress data =food inherit __str__ method print(and str(run __str__ you can also fetch and save the listing output as string without printing it with strand interactive echoes still use the default format because we're left __repr__ as an option for clientsdisplay str(xprint this to interpret escapes display ' designing with classes the __repr__ still is default |
1,519 | have one or more superclasses this is where multiple inheritance comes in handyby adding listinstance to the list of superclasses in class header ( mixing it in)you get its __str__ "for freewhile still inheriting from the existing superclass(esthe file testmixin py demonstrates with first-cut testing scriptfile testmixin py from listinstance import listinstance get lister tool class class superdef __init__(self)self data 'spamdef ham(self)pass class sub(superlistinstance)def __init__(self)super __init__(selfself data 'eggsself data def spam(self)pass if __name__ ='__main__' sub(print(xsuperclass __init__ create instance attrs mix in ham and __str__ listers have access to self more instance attrs define another method here run mixed-in __str__ heresub inherits names from both super and listinstanceit' composite of its own names and names in both its superclasses when you make sub instance and print ityou automatically get the custom representation mixed in from listinstance (in this casethis script' output is the same under both python and xexcept for object addresseswhich can naturally vary per process) :\codepython testmixin py <instance of subaddress data =spam data =eggs data = this testmixin testing script worksbut it hardcodes the tested class' name in the codeand makes it difficult to experiment with alternatives--as we will in moment to be more flexiblewe can borrow page from ' module reloadersand pass in the object to be testedas in the following improved test scripttestmixin--the one actually used by all the lister class modulesself-test code in this context the object passed in to the tester is mix-in class instead of functionbut the principle is similareverything qualifies as passable "first classobject in python#!python file testmixin py ( ""generic lister mixin testersimilar to transitive reloader in but passes class object to tester (not function)multiple inheritance"mix-inclasses |
1,520 | strings herein keeping with ' factories pattern ""import importlib def tester(listerclasssept=false)class superdef __init__(self)self data 'spamdef ham(self)pass superclass __init__ create instance attrs class sub(superlisterclass)def __init__(self)super __init__(selfself data 'eggsself data def spam(self)pass mix in ham and __str__ listers have access to self instance sub(print(instanceif septprint('- return instance with lister' __str__ run mixed-in __str__ (or via str( )more instance attrs define another method here def testbynames(modnameclassnamesept=false)modobject importlib import_module(modnameimport by namestring listerclass getattr(modobjectclassnamefetch attr by namestring tester(listerclassseptif __name__ ='__main__'testbynames('listinstance''listinstance'truetestbynames('listinherited''listinherited'truetestbynames('listtree''listtree'falsetest all three here while it' at itthis script also adds the ability to specify test module and class by name stringand leverages this in its self-test code--an application of the factory pattern' mechanics described earlier here is the new script in actionbeing run by the lister module that imports it to test its own class (with the same results in and again)we can run the test script itself toobut that mode tests the two lister variantswhich we have yet to see (or code!) :\codepython listinstance py <instance of subaddress data =spam data =eggs data = :\codepython testmixin py <instance of subaddress data =spam data =eggs data = designing with classes |
1,521 | and tests of two other lister classes coming up the listinstance class we've coded so far works in any class it' mixed into because self refers to an instance of the subclass that pulls this class inwhatever that may be againin sensemix-in classes are the class equivalent of modules--packages of methods useful in variety of clients for examplehere is listinstance working again in single-inheritance mode on different class' instancesloaded with importand displaying attributes assigned outside the classimport listinstance class (listinstance listinstance)pass ( ax bx print( <instance of caddress = = = besides the utility they providemix-ins optimize code maintenancelike all classes do for exampleif you later decide to extend listinstance' __str__ to also print all the class attributes that an instance inheritsyou're safebecause it' an inherited methodchanging __str__ automatically updates the display of each subclass that imports the class and mixes it in and since it' now officially "later,let' move on to the next section to see what such an extension might look like listing inherited attributes with dir as it isour listerinstance mix-in displays instance attributes only ( names attached to the instance object itselfit' trivial to extend the class to display all the attributes accessible from an instancethough--both its own and those it inherits from its classes the trick is to use the dir built-in function instead of scanning the instance' __dict__ dictionarythe latter holds instance attributes onlybut the former also collects all inherited attributes in python and later the following mutation codes this schemei've coded this in its own module to facilitate simple testingbut if existing clients were to use this version instead they would pick up the new display automatically (and recall from that an import' as clause can rename new version to prior name being used)#!python file listinherited py ( xclass listinherited""use dir(to collect both instance attrs and names inherited from its classespython shows more names than because of the implied object superclass in the new-style class modelgetattr(multiple inheritance"mix-inclasses |
1,522 | __repr__or else this loops when printing bound methods""def __attrnames(self)result 'for attr in dir(self)instance dir(if attr[: ='__and attr[- :='__'skip internals result +'\ % \nattr elseresult +'\ % =% \ (attrgetattr(selfattr)return result def __str__(self)return 'self __class__ __name__id(self)self __attrnames()my class' name my address name=value list if __name__ ='__main__'import testmixin testmixin tester(listinheritednotice that this code skips __x__ namesvaluesmost of these are internal names that we don' generally care about in generic listing like this this version also must use the getattr built-in function to fetch attributes by name string instead of using instance attribute dictionary indexing--getattr employs the inheritance search protocoland some of the names we're listing here are not stored on the instance itself to test the new versionrun its file directly--it passes the class it defines to the testmixin py file' test function to be used as mix-in in subclass this output of this test and lister class varies per releasethoughbecause dir results differ in python xwe get the followingnotice the name mangling at work in the lister' method name ( truncated some of the full value displays to fit on this page) :\codec:\python \python listinherited py <instance of subaddress _listinherited__attrnames=__doc__ __init__ __module__ __str__ data =spam data =eggs data = ham=spam=in python xmore attributes are displayed because all classes are "new styleand inherit names from the implied object superclassmore on this in because so many names are inherited from the default superclassi've omitted many here-there are in total in run this on your own for the full listing designing with classes |
1,523 | <instance of subaddress _listinherited__attrnames=__class__ __delattr__ __dict__ __dir__ __doc__ __eq__ more names omitted total __repr__ __setattr__ __sizeof__ __str__ __subclasshook__ __weakref__ data =spam data =eggs data = hamsub more >spamsub more >as one possible improvement to address the proliferation of inherited built-in names and long values herethe following alternative for ___attrnames in file listinherited py of the book example' package groups the double-underscore names separatelyand minimizes line wrapping for large attribute valuesnotice how it escapes with %so that just one remains for the final formatting operation at the enddef __attrnames(selfindent='* )result 'unders% \ % %% \nothers% \ ('-'* indent'-'* unders [for attr in dir(self)instance dir(if attr[: ='__and attr[- :='__'skip internals unders append(attrelsedisplay str(getattr(selfattr))[: -(len(indentlen(attr))result +'% % =% \ (indentattrdisplayreturn result 'join(underswith this changethe class' test output is bit more sophisticatedbut also more concise and usablec:\codec:\python \python listinherited py <instance of subaddress unders__doc____init____module____str__ others_listinherited__attrnames=<bound method sub __attrnames of <testmixin sub insta data =spam data =eggs data = ham=spam=multiple inheritance"mix-inclasses |
1,524 | <instance of subaddress unders__class____delattr____dict____dir____doc____eq____format____ge____getattribute____gt____hash____init____le____lt____module____ne____new____qualname____reduce____reduce_ex____repr____setattr____sizeof____str____subclasshook____weakref__ others_listinherited__attrnames=<bound method sub __attrnames of <testmixin tester < data =spam data =eggs data = hamsub object at spamsub object at display format is an open-ended problem ( python' standard pprint "pretty printermodule may offer options here too)so we'll leave further polishing as suggested exercise the tree lister of the next section may be more useful in any event looping in __repr__one caution here--now that we're displaying inherited methods toowe have to use __str__ instead of __repr__ to overload printing with __repr__this code will fall into recursive loops --displaying the value of method triggers the __repr__ of the method' classin order to display the class that isif the lister' __repr__ tries to display methoddisplaying the method' class will trigger the lister' __repr__ again subtlebut truechange __str__ to __repr__ here to see this for yourself if you must use __repr__ in such contextyou can avoid the loops by using isinstance to compare the type of attribute values against types methodtype in the standard libraryto know which items to skip listing attributes per object in class trees let' code one last extension as it isour latest lister includes inherited namesbut doesn' give any sort of designation of the classes from which the names are acquired as we saw in the classtree py example near the end of thoughit' straightforward to climb class inheritance trees in code the following mix-in classcoded in the file listtree pymakes use of this same technique to display attributes grouped by the classes they live in--it sketches the full physical class treedisplaying attributes attached to each object along the way the reader must still infer attribute inheritancebut this gives substantially more detail than simple flat list#!python file listtree py ( xclass listtree""mix-in that returns an __str__ trace of the entire class tree and all designing with classes |
1,525 | constructed stringuses __x attr names to avoid impacting clientsrecurses to superclasses explicitlyuses str format(for clarity""def __attrnames(selfobjindent)spaces (indent result 'for attr in sorted(obj __dict__)if attr startswith('__'and attr endswith('__')result +spaces '{ }\nformat(attrelseresult +spaces '{ }={ }\nformat(attrgetattr(objattr)return result def __listclass(selfaclassindent)dots indent if aclass in self __visitedreturn '\ { }\nformatdotsaclass __name__id(aclass)elseself __visited[aclasstrue here self __attrnames(aclassindentabove 'for super in aclass __bases__above +self __listclass(superindent+ return '\ { }\nformatdotsaclass __name__id(aclass)hereabovedotsdef __str__(self)self __visited {here self __attrnames(self above self __listclass(self __class__ return 'formatself __class__ __name__id(self)hereaboveif __name__ ='__main__'import testmixin testmixin tester(listtreethis class achieves its goal by traversing the inheritance tree--from an instance' __class__ to its classand then from the class' __bases__ to all superclasses recursivelyscanning each object' attribute __dict__ along the way ultimatelyit concatenates each tree portion' string as the recursion unwinds it can take while to understand recursive programs like thisbut given the arbitrary shape and depth of class treeswe really have no choice here (apart from explicit stack multiple inheritance"mix-inclasses |
1,526 | simplerand which we'll omit here for space and timethis class is coded to keep its business as explicit as possiblethoughto maximize clarity for exampleyou could replace the __listclass method' loop statement in the first of the following with the implicitly run generator expression in the secondbut the second seems unnecessarily convoluted in this context--recursive calls embedded in generator expression--and has no obvious performance advantageespecially given this program' limited scope (neither alternative makes temporary listthough the first may create more temporary results depending on the internal implementation of stringsconcatenationand join--something you' need to time with ' tools to determine)or above 'for super in aclass __bases__above +self __listclass(superindent+ above 'joinself __listclass(superindent+ for super in aclass __bases__you could also code the else clause in __listclass like the followingas in the prior edition of this book--an alternative that embeds everything in the format arguments listrelies on the fact that the join call kicks off the generator expression and its recursive calls before the format operation even begins building up the result textand seems more difficult to understanddespite the fact that wrote it (never good sign!)self __visited[aclasstrue genabove (self __listclass(cindent+ for in aclass __bases__return '\ { }\nformatdotsaclass __name__id(aclass)self __attrnames(aclassindent)runs before format'join(genabove)dotsas alwaysexplicit is better than implicitand your code can be as big factor in this as the tools it uses also notice how this version uses the python and string format method instead of formatting expressionsin an effort to make substitutions arguably clearerwhen many substitutions are applied like thisexplicit argument numbers may make the code easier to decipher in shortin this version we exchange the first of the following lines for the secondreturn 'expression return 'formatmethod this policy has an unfortunate downside in and toobut we have to run the code to see why designing with classes |
1,527 | nowto testrun this class' module file as beforeit passes the listtree class to testmixin py to be mixed in with subclass in the test function the file' tree-sketcher output in python is as followsc:\codec:\python \python listtree py <instance of subaddress _listtree__visited={data =spam data =eggs data = <class subaddress __doc__ __init__ __module__ spam<class superaddress __doc__ __init__ __module__ ham<class listtreeaddress _listtree__attrnames_listtree__listclass__doc__ __module__ __str__ notice in this output how methods are unbound now under xbecause we fetch them from classes directly in the previous section' version they displayed as bound methodsbecause listinherited fetched these from instances with getattr instead (the first version indexed the instance __dict__ and did not display inherited methods on classes at allalso observe how the lister' __visited table has its name mangled in the instance' attribute dictionaryunless we're very unluckythis won' clash with other data there some of the lister class' methods are mangled for pseudoprivacy as well under python in the followingwe again get extra attributes which may vary within the lineand extra superclasses--as we'll learn in the next all top-level classes inherit from the built-in object class automatically in xpython classes do so manually if they desire new-style class behavior also notice that the attributes that were unbound methods in are simple functions in xas described earlier in this (and that againi've deleted most built-in attributes in object to save space hererun this on your own for the complete listing)multiple inheritance"mix-inclasses |
1,528 | <instance of subaddress _listtree__visited={data =spam data =eggs data = <class subaddress __doc__ __init__ __module__ __qualname__ spamsub spam at <class superaddress __dict__ __doc__ __init__ __module__ __qualname__ __weakref__ hamsuper ham at <class objectaddress __class__ __delattr__ __dir__ __doc__ __eq__ more omitted total __repr__ __setattr__ __sizeof__ __str__ __subclasshook__ <class listtreeaddress _listtree__attrnames_listtree__listclass__dict__ __doc__ __module__ __qualname__ __str__ __weakref__ this version avoids listing the same class object twice by keeping table of classes visited so far (this is why an object' id is included--to serve as key for previously designing with classes |
1,529 | dictionary works to avoid repeats in the output because class objects are hashable and thus may be dictionary keysa set would provide similar functionality technicallycycles are not generally possible in class inheritance trees-- class must already have been defined to be named as superclassand python raises an exception as it should if you attempt to create cycle later by __bases__ changes--but the visited mechanism here avoids relisting class twiceclass cpass class ( )pass __bases__ ( ,deepdark magictypeerrora __bases__ item causes an inheritance cycle usage variationshowing underscore name values this version also takes care to avoid displaying large internal objects by skipping __x__ names again if you comment out the code that treats these names speciallyfor attr in sorted(obj __dict__)if attr startswith('__'and attr endswith('__')result +spaces '{ }\nformat(attrelseresult +spaces '{ }={ }\nformat(attrgetattr(objattr)then their values will display normally here' the output in with this temporary change madegiving the values of every attribute in the class treec:\codec:\python \python listtree py <instance of subaddress _listtree__visited={data =spam data =eggs data = <class subaddress __doc__=none __init____module__=testmixin spam<class superaddress __doc__=none __init____module__=testmixin ham<class listtreeaddress _listtree__attrnames_listtree__listclass__doc__mix-in that returns an __str__ trace of the entire class tree and all its objectsattrs at and above selfrun by print()str(returns multiple inheritance"mix-inclasses |
1,530 | recurses to superclasses explicitlyuses str format(for clarity__module__=__main__ __str__this test' output is much larger in and may justify isolating underscore names in general as we did earlier in factthis test may not even work in some currently recent releases as isc:\codec:\python \python listtree py etc file "listtree py"line in __attrnames result +spaces '{ }={ }\nformat(attrgetattr(objattr)typeerrortype method_descriptor doesn' define __format__ debated recoding to work around this issuebut it serves as fair example of debugging requirements and techniques in dynamic open source project like python per the following notethe str format call no longer supports certain object types that are the values of built-in attribute names--yet another reason these names are probably better skipped debugging str format issuein xrunning the commented-out version works in and but there seems to be bugor at least regressionhere in and --these pythons fail with an exception because five built-in methods in object do not define __format__ expected by str formatand the default in object is apparently no longer applied correctly in such cases with empty and generic formatting targets to see this liveit' enough to run simplified code that isolates the problemc:\codepy - '{ }format(object __reduce__" :\codepy - '{ }format(object __reduce__typeerrortype method_descriptor doesn' define __format__ per both prior behavior and current python documentationempty targets like this are supposed to convert the object to its str print string (see both the original pep and the language reference manualoddlythe { and { :sstring targets both now failbut the { !sforced str conversion target worksas does manual str preconversion --apparently reflecting change for type-specific case that neglected perhaps more common generic usage modesc:\codepy - '{ : }format(object __reduce__typeerrortype method_descriptor doesn' define __format__ '{ ! }format(object __reduce__" designing with classes |
1,531 | "to fixwrap the format call in try statement to catch the exceptionuse formatting expressions instead of the str format methoduse one of the aforementioned still-working str format usage modes and hope it does not change tooor wait for repair of this in later release here' the recommended workaround using the tried-and-true (it' also noticeably shorterbut won' repeat ' comparisons here) :\codepy - '%sobject __reduce__ "to apply this in the tree lister' codechange the first of these to its followerresult +spaces '{ }={ }\nformat(attrgetattr(objattr)result +spaces '% =% \ (attrgetattr(objattr)python has the same regression in but not --inherited from the changeapparently--but does not show object methods in this example since this example generates too much output in anyhowit' moot point herebut is decent example of real-world coding unfortunatelyusing newer features like str format sometimes puts your code in the awkward position of beta tester in the current lineusage variationrunning on larger modules for more fununcomment the underscore handler lines to enable them againand try mixing this class into something more substantiallike the button class of python' tkinter gui toolkit module in generalyou'll want to name listtree first (leftmostin class headerso its __str__ is picked upbutton has onetooand the leftmost superclass is always searched first in multiple inheritance the output of the following is fairly massive ( characters and lines in --and if you forget to uncomment the underscore detection!)so run this code on your own to see the full listing notice how our lister' __visited dictionary attribute mixes harmlessly with those created by tkinter itself if you're using python xalso recall that you should use tkinter for the module name instead of tkinterfrom listtree import listtree from tkinter import button class mybutton(listtreebutton)pass mybutton(text='spam'open('savetree txt'' 'write(str( ) len(open('savetree txt'readlines() print( <instance of mybuttonaddress both classes have __str__ listtree firstuse its __str__ save to file for later viewing lines in the file print the display here multiple inheritance"mix-inclasses |
1,532 | _name= _tclcommands=[_w children={mastermuch more omitted str(bprint( [: ]or print just the first part experiment arbitrarily on your own the main point here is that oop is all about code reuseand mix-in classes are powerful example like almost everything else in programmingmultiple inheritance can be useful device when applied well in practicethoughit is an advanced feature and can become complicated if used carelessly or excessively we'll revisit this topic as gotcha at the end of the next collector module finallyto make importing our tools even easierwe can provide collector module that combines them in single namespace--importing just the following gives access to all three lister mix-ins at oncefile lister py collect all three listers in one module for convenience from listinstance import listinstance from listinherited import listinherited from listtree import listtree lister listtree choose default lister importers can use the individual class names as isor alias them to common name used in subclasses that can be modified in the import statementimport lister lister listinstance lister lister use specific lister use lister default from lister import lister lister use lister default from lister import listinstance as lister lister use lister alias python often makes flexible tool apis nearly automatic designing with classes |
1,533 | like most softwarethere' much more we could do here the following gives some pointers on extensions you may wish to explore some are interesting projectsand two serve as segue to the next but for space will have to remain in the suggested exercise category here general ideasguisbuilt-ins grouping double-underscore names as we did earlier may help reduce the size of the tree displaythough some like __init__ are user-defined and may merit special treatment sketching the tree in gui might be natural next step too--the tkinter toolkit that we utilized in the prior section' lister examples ships with python and provides basic but easy supportand others offer richer but more complex alternatives see the notes at the end of ' case study for more pointers in this department physical trees versus inheritanceusing the mro (previewin the next we'll also meet the new-style class modelwhich modifies the search order for one special multiple inheritance case (diamondstherewe'll also study the class __mro__ new-style class object attribute-- tuple giving the class tree search order used by inheritanceknown as the new-style mro as isour listtree tree lister sketches the physical shape of the inheritance treeand expects the viewer to infer from this where an attribute is inherited from this was its goalbut general object viewer might also use the mro tuple to automatically associate an attribute with the class from which it is inherited--by scanning the new-style mro (or the classic classesdflr orderingfor each inherited attribute in dir resultwe can simulate python' inheritance searchand map attributes to their source objects in the physical class tree displayed in factwe will write code that comes very close to this idea in the next mapattrs moduleand reuse this example' test classes there to demonstrate the ideaso stay tuned for an epilogue to this story this might be used instead of or in addition to displaying attribute physical locations in __attrnames hereboth forms might be useful data for programmers to see this approach is also one way to deal with slotsthe topic of the next note virtual dataslotspropertiesand more (previewbecause they scan instance __dict__ namespace dictionariesthe listinstance and listtree classes presented here raise some subtle design issues in python classessome names associated with instance data may not be stored at the instance itself this includes topics presented in the next such as new-style propertiesslotsand descriptorsbut also attributes dynamically computed in all classes with tools like __getattr__ none of these "virtualattributesnames are stored in an instance' namespace dictionaryso none will be displayed as part of an instance' own data multiple inheritance"mix-inclasses |
1,534 | on instanceseven though their names don' appear in instance namespace dictionaries properties and descriptors are associated with instances toobut they don' reserve space in the instancetheir computed nature is much more explicitand they may seem closer to class-level methods than instance data as we'll see in the next slots function like instance attributesbut are created and managed by automatically created items in classes they are relatively infrequently used new-style class optionwhere instance attributes are declared in __slots__ class attributeand not physically stored in an instance' __dict__in factslots may suppress __dict__ entirely because of thistools that display instances by scanning their namespaces alone won' directly associate the instance with attributes stored in slots as islisttree displays slots as class attributes wherever they appear (though not at the instance)and listinstance doesn' display them at all though this will make more sense after we study this feature in the next it impacts code here and similar tools for exampleif in textmixin py we assign __slots__=['data 'in super and __slots__=['data 'in subonly the data attribute is displayed in the instance by these two lister classes listtree also displays data and data but as attributes of the super and sub class objects and with special format for their values (technicallythey are class-level descriptorsanother new-style tool introduced in the next as the next will explainto show slot attributes as instance namestools generally need to use dir to get list of all attributes--both physically present and inherited--and then use either getattr to fetch their values from the instanceor fetch values from their inheritance source via __dict__ in tree scans and accept the display of the implementations of some at classes because dir includes the names of inherited "virtualattributes--including both slots and properties--they would be included in the instance set as we'll also findthe mro might assist here to map dir attribute to their sourcesor restrict instance displays to names coded in user-defined classes by filtering out names inherited from the built-in object listinherited is immune to most of thisbecause it already displays the full dir results setwhich include both __dict__ names and all classes__slots__ namesthough its display is of marginal use as is listtree variant using the dir technique along with the mro sequence to map attributes to classes would apply to slots toobecause slots-based names appear in class' __dict__ results individually as slot management toolsthough not in the instance __dict__ alternativelyas policy we could simply let our code handle slot-based attributes as it currently doesrather than complicating it for rarely usedadvanced feature that' even questionable practice today slots and normal instance attributes are different kinds of names in factdisplaying slots names as attributes of classes instead of instances is technically more accurate--as we'll see in the next their implementation is at classesthough their space is at instances designing with classes |
1,535 | may be bit of pipe dream anyhow techniques like those outlined here may address slots and propertiesbut some attributes are entirely dynamicwith no physical basis at allthose computed on fetch by generic method such as __get attr__ are not data in the classic sense tools that attempt to display data in wildly dynamic language python must come with the caveat that some data is ethereal at bestwe'll also make minor extension to this section' code in the exercises at the end of this part of the bookto list superclass names in parentheses at the start of instance displaysso keep it filed for future reference for now to better understand the last of the preceding two pointswe need to wrap up this and move on to the next and last in this part of the book other design-related topics in this we've studied inheritancecompositiondelegationmultiple inheritancebound methodsand factories--all common patterns used to combine classes in python programs we've really only scratched the surface here in the design patterns domainthough elsewhere in this book you'll find coverage of other design-related topicssuch asabstract superclasses (decorators and type subclasses (static and class methods (managed attributes and metaclasses and for more details on design patternsthoughwe'll delegate to other resources on oop at large although patterns are important in oop work and are often more natural in python than other languagesthey are not specific to python itselfand subject that' often best acquired by experience summary in this we sampled common ways to use and combine classes to optimize their reusability and factoring benefits--what are usually considered design issues that are often independent of any particular programming language (though python can make them easier to implementwe studied delegation (wrapping objects in proxy classes)composition (controlling embedded objects)and inheritance (acquiring behavior from other classes)as well as some more esoteric concepts such as pseudoprivate attributesmultiple inheritancebound methodsand factories summary |
1,536 | python--if not for your codethen for the code of others you may need to understand firstthoughhere' another quick quiz to review test your knowledgequiz what is multiple inheritance what is delegation what is composition what are bound methods what are pseudoprivate attributes used fortest your knowledgeanswers multiple inheritance occurs when class inherits from more than one superclassit' useful for mixing together multiple packages of class-based code the left-toright order in class statement headers determines the general order of attribute searches delegation involves wrapping an object in proxy classwhich adds extra behavior and passes other operations to the wrapped object the proxy retains the interface of the wrapped object composition is technique whereby controller class embeds and directs number of objectsand provides an interface all its ownit' way to build up larger structures with classes bound methods combine an instance and method functionyou can call them without passing in an instance object explicitly because the original instance is still available pseudoprivate attributes (whose names begin but do not end with two leading underscores__xare used to localize names to the enclosing class this includes both class attributes like methods defined inside the classand self instance attributes assigned inside the class' methods such names are expanded to include the class namewhich makes them generally unique designing with classes |
1,537 | advanced class topics this concludes our look at oop in python by presenting few more advanced class-related topicswe will survey subclassing built-in types"new styleclass changes and extensionsstatic and class methodsslots and propertiesfunction and class decoratorsthe mro and the super calland more as we've seenpython' oop model isat its corerelatively simpleand some of the topics presented in this are so advanced and optional that you may not encounter them very often in your python applications-programming career in the interest of completenessthough--and because you never know when an "advancedtopic may crop up in code you use--we'll round out our discussion of classes with brief look at these advanced tools for oop work as usualbecause this is the last in this part of the bookit ends with section on class-related "gotchas,and the set of lab exercises for this part encourage you to work through the exercises to help cement the ideas we've studied here also suggest working on or studying larger oop python projects as supplement to this book as with much in computingthe benefits of oop tend to become more apparent with practice content notesthis collects advanced class topicsbut some are too large for this to cover well topics such as propertiesdescriptorsdecoratorsand metaclasses are mentioned only briefly hereand given fuller treatment in the final part of this bookafter exceptions be sure to look ahead for more complete examples and extended coverage of some of the subjects that fall into this category you'll also notice that this is the largest in this book-- ' assuming that readers courageous enough to take on this topics are ready to roll up their sleeves and explore its in-depth coverage if you're not looking for advanced oop topicsyou may wish to skip ahead to end materialsand come back here when you confront these tools in the code of your programming future |
1,538 | extending built-in types besides implementing new kinds of objectsclasses are sometimes used to extend the functionality of python' built-in types to support more exotic data structures for instanceto add queue insert and delete methods to listsyou can code classes that wrap (embeda list object and export insert and delete methods that process the list speciallylike the delegation technique we studied in as of python you can also use inheritance to specialize built-in types the next two sections show both techniques in action extending types by embedding do you remember those set functions we wrote in and here' what they look like brought back to life as python class the following example (the file setwrapper pyimplements new set object type by moving some of the set functions to methods and adding some basic operator overloading for the most partthis class just wraps python list with extra set operations but because it' classit also supports multiple instances and customization by inheritance in subclasses unlike our earlier functionsusing classes here allows us to make multiple self-contained set objects with preset data and behaviorrather than passing lists into functions manuallyclass setdef __init__(selfvalue [])self data [self concat(valueconstructor manages list def intersect(selfother)res [for in self dataif in otherres append(xreturn set(resother is any sequence self is the subject def union(selfother)res self data[:for in otherif not in resres append(xreturn set(resother is any sequence copy of my list add items in other def concat(selfvalue)for in valueif not in self dataself data append(xvaluelistset removes duplicates pick common items return new set def __len__(self)return len(self datadef __getitem__(selfkey)return self data[keydef __and__(selfother)return self intersect(otherdef __or__(selfother)return self union(other advanced class topics len(self)if self self[ ]self[ :jself other self other |
1,539 | def __iter__(self)return 'set:repr(self dataprint(self)return iter(self datafor in selfto use this classwe make instancescall methodsand run defined operators as usualfrom setwrapper import set set([ ]print( union(set([ ]))print( set([ ])prints set:[ prints set:[ overloading operations such as indexing and iteration also enables instances of our set class to often masquerade as real lists because you will interact with and extend this class in an exercise at the end of this won' say much more about this code until appendix extending types by subclassing beginning with python all the built-in types in the language can now be subclassed directly type-conversion functions such as liststrdictand tuple have become built-in type names--although transparent to your scripta type-conversion call ( list('spam')is now really an invocation of type' object constructor this change allows you to customize or extend the behavior of built-in types with userdefined class statementssimply subclass the new type names to customize them instances of your type subclasses can generally be used anywhere that the original builtin type can appear for examplesuppose you have trouble getting used to the fact that python list offsets begin at instead of not to worry--you can always code your own subclass that customizes this core behavior of lists the file typesubclass py shows howsubclass built-in list type/class map to - call back to built-in version class mylist(list)def __getitem__(selfoffset)print('(indexing % at % )(selfoffset)return list __getitem__(selfoffset if __name__ ='__main__'print(list('abc') mylist('abc'print(x__init__ inherited from list __repr__ inherited from list print( [ ]print( [ ]mylist __getitem__ customizes list superclass method append('spam')print(xx reverse()print(xattributes from list superclass in this filethe mylist subclass extends the built-in list' __getitem__ indexing method onlyto map indexes to back to the required to - all it really does is decrement extending built-in types |
1,540 | enough to do the trickpython typesubclass py [' '' '' '[' '' '' '(indexing [' '' '' 'at (indexing [' '' '' 'at [' '' '' ''spam'['spam'' '' '' 'this output also includes tracing text the class prints on indexing of coursewhether changing indexing this way is good idea in general is another issue--users of your mylist class may very well be confused by such core departure from python sequence behaviorthe ability to customize built-in types this way can be powerful assetthough for instancethis coding pattern gives rise to an alternative way to code set--as subclass of the built-in list typerather than standalone class that manages an embedded list object as shown in the prior section as we learned in python today comes with powerful built-in set objectalong with literal and comprehension syntax for making new sets coding one yourselfthoughis still great way to learn about type subclassing in general the following classcoded in the file setsubclass pycustomizes lists to add just methods and operators related to set processing because all other behavior is inherited from the built-in list superclassthis makes for shorter and simpler alternative--everything not defined here is routed to list directlyfrom __future__ import print_function compatibility class set(list)def __init__(selfvalue [])list __init__([]self concat(valueconstructor customizes list copies mutable defaults def intersect(selfother)res [for in selfif in otherres append(xreturn set(resother is any sequence self is the subject def union(selfother)res set(selfres concat(otherreturn res other is any sequence copy me and my list def concat(selfvalue)for in valueif not in selfvaluelistsetetc removes duplicates advanced class topics pick common items return new set |
1,541 | def __and__(selfother)return self intersect(otherdef __or__(selfother)return self union(otherdef __repr__(self)return 'set:list __repr__(selfif __name__ ='__main__' set([ , , , ] set([ , , , , ]print(xylen( )print( intersect( ) union( )print( yx yx reverse()print(xhere is the output of the self-test code at the end of this file because subclassing core types is somewhat advanced feature with limited target audiencei'll omit further details herebut invite you to trace through these results in the code to study its behavior (which is the same on python and )python setsubclass py set:[ set:[ set:[ set:[ set:[ set:[ set:[ there are more efficient ways to implement sets with dictionaries in pythonwhich replace the nested linear search scans in the set implementations shown here with more direct dictionary index operations (hashingand so run much quicker for more detailssee the continuation of this thread in the follow-up book programming python againif you're interested in setsalso take another look at the set object type we explored in this type provides extensive set operations as built-in tools set implementations are fun to experiment withbut they are no longer strictly required in python today for another type subclassing exampleexplore the implementation of the bool type in python and later as mentioned earlier in the bookbool is subclass of int with two instances (true and falsethat behave like the integers and but inherit custom string-representation methods that display their names the "new styleclass model in release python introduced new flavor of classesknown as new-style classesclasses following the original and traditional model became known as classic classes when compared to the new kind in the class story has mergedbut it remains split for python users and codein python xall classes are automatically what were formerly called "new style,whether they explicitly inherit from object or not coding the object superclass is optional and implied the "new styleclass model |
1,542 | to be considered "new styleand enable and obtain all new-style behavior classes without this are "classic because all classes are automatically new-style in xthe features of new-style classes are simply normal class features in that line 've opted to keep their descriptions in this section separatehoweverin deference to users of python code--classes in such code acquire new-style features and behavior only when they are derived from object in other wordswhen python users see descriptions of "new styletopics in this bookthey should take them to be descriptions of existing properties of their classes for readersthese are set of optional changes and extensions that you may choose to enable or notunless the code you must use already employs them in python xthe identifying syntactic difference for new-style classes is that they are derived from either built-in typesuch as listor special built-in class known as object the built-in name object is provided to serve as superclass for new-style classes if no other built-in type is appropriate to useclass newstyle(object)normal class code explicit new-style derivation not required in xautomatic any class derived from objector any other built-in typeis automatically treated as new-style class that isas long as built-in type is somewhere in its superclass treea class acquires new-style class behavior and extensions classes not derived from built-ins such as object are considered classic just how new is new-styleas we'll seenew-style classes come with profound differences that impact programs broadlyespecially when code leverages their added advanced features in factat least in terms of its oop supportthese changes on some levels transform python into different language altogether--one that' mandated in the lineone that' optional in only if ignored by every programmerand one that borrows much more from (and is often as complex asother languages in this domain new-style classes stem in part from an attempt to merge the notion of class with that of type around the time of python though they went unnoticed by many until they were escalated to required knowledge in you'll need to judge the success of that merging for yourselfbut as we'll seethere are still distinctions in the model--now between class and metaclass--and one of its side effects is to make normal classes more powerful but also substantially more complex the new-style inheritance algorithm formalized in for examplegrows in complexity by at least factor of stillsome programmers using straightforward application code may notice only slight divergence from traditional "classicclasses after allwe've managed to get to this point in this book writing substantial class exampleswith mostly just passing mentions advanced class topics |
1,543 | it has for some two decades howeverbecause they modify core class behaviorsnew-style classes had to be introduced in python as distinct tool so as to avoid impacting any existing code that depends on the prior model for examplesome subtle differencessuch as diamond pattern inheritance search and the interaction of built-in operations and managed attribute methods such as __getattr__ can cause some existing code to fail if left unchanged using optional extensions in the new model such as slots can have the same effect the class model split is removed in python xwhich mandates new-style classesbut it still exists for readers using xor reusing the vast amount of existing code in production use because this has been an optional extension in xcode written for that line may use either class model the next two top-level sections provide overviews of the ways in which new-style classes differ and the new tools they provide these topics represent potential changes to some python readersbut simply additional advanced class topics to many python readers if you're in the latter groupyou'll find full coverage herethough some of it is presented in the context of changes--which you can accept as featuresbut only if you never must deal with any of the millions of lines of existing code new-style class changes new-style classes differ from classic classes in number of wayssome of which are subtle but can impact both existing code and common coding styles as preview and summaryhere are some of the most prominent ways they differattribute fetch for built-insinstance skipped the __getattr__ and __getattribute__ generic attribute interception methods are still run for attributes accessed by explicit namebut no longer for attributes implicitly fetched by built-in operations they are not called for __x__ operator overloading method names in built-in contexts only--the search for such names begins at classesnot instances this breaks or complicates objects that serve as proxies for another object' interfaceif wrapped objects implement operator overloading as data pointthe book programming pythona , -page applications programming follow-up to this book that uses exclusivelyneither uses nor needs to accommodate any of the new-style class tools of this and still manages to build significant programs for guiswebsitessystems programmingdatabasesand text it' mostly straightforward code that leverages built-in types and libraries to do its worknot obscure and esoteric oop extensions when it does use classesthey are relatively simpleproviding structure and code factoring that book' code is also probably more representative of realworld programming than some in this language tutorial text--which suggests that many of python' advanced oop tools may be artificialhaving more to do with language design than practical program goals then againthat book has the luxury of restricting its toolset to such codeas soon as your coworker finds way to use an arcane language featureall bets are offnew-style class changes |
1,544 | classes and types mergedtype testing classes are now typesand types are now classes in factthe two are essentially synonymsthough the metaclasses that now subsume types are still somewhat distinct from normal classes the type(ibuilt-in returns the class an instance is made frominstead of generic instance typeand is normally the same as __class__ moreoverclasses are instances of the type classand type may be subclassed to customize class creation with metaclasses coded with class statements this can impact code that tests types or otherwise relies on the prior type model automatic object root classdefaults all new-style classes (and hence typesinherit from objectwhich comes with small set of default operator overloading methods ( __repr__in xthis class is added automatically above the user-defined root ( topmostclasses in treeand need not be listed as superclass explicitly this can affect code that assumes the absence of method defaults and root classes inheritance search ordermro and diamonds diamond patterns of multiple inheritance have slightly different search order-roughlyat diamonds they are searched across before upand more breadth-first than depth-first this attribute search orderknown as the mrocan be traced with new __mro__ attribute available on new-style classes the new search order largely applies only to diamond class treesthough the new model' implied object root itself forms diamond in all multiple inheritance trees code that relies on the prior order will not work the same inheritance algorithm the algorithm used for inheritance in new-style classes is substantially more complex than the depth-first model of classic classesincorporating special cases for descriptorsmetaclassesand built-ins we won' be able to formalize this until after we've studied metaclasses and descriptors in more depthbut it can impact code that does not anticipate its extra convolutions new advanced toolscode impacts new-style classes have set of new class toolsincluding slotspropertiesdescriptorssuperand the __getattribute__ method most of these have very specific tool-building purposes their use can also impact or break existing codethoughslotsfor examplesometimes prevent creation of an instance namespace dictionary altogetherand generic attribute handlers may require different coding we'll explore the extensions noted in the last of these items in later top-level section of its ownand will defer formal inheritance algorithm coverage until as noted because the other items on this list have the potential to break traditional python codethoughlet' take closer look at each in turn here advanced class topics |
1,545 | and xeven though they are an option in the latter this and book sometimes label features as changes to contrast with traditional codebut some are technically introduced by new-style classes--which are mandated in xbut can show up in code too for spacethis distinction is called out often but not dogmatically here complicating this distinctionsome class-related changes owe to new-style classes ( skipping __getattr__ for operator methodsbut some do not ( replacing unbound methods with functionsmoreovermany programmers stick to classic classesignoring what they view as feature new-style classes are not newthoughand apply to both pythons--if they appear in codethey're required reading for users too attribute fetch for built-ins skips instances we introduced this new-style class change in sidebars in both and because of their impact on prior examples and topics in new-style classes (and hence all classes in )the generic instance attribute interception methods __get attr__ and __getattribute__ are no longer called by built-in operations for __x__ operator overloading method names--the search for such names begins at classesnot instances attributes accessed by explicit namehoweverare routed through these methodseven if they are __x__ names hencethis is primarily change to the behavior of built-in operations more formallyif class defines __getitem__ index overload method and is an instance of this classthen an index expression like [iis roughly equivalent to __geti tem__(ifor classic classesbut type(x__getitem__(xifor new-style classes--the latter beginning its search in the classand thus skipping __getattr__ step from the instance for an undefined name technicallythis method search for built-in operations like [iuses normal inheritance beginning at the class leveland inspects only the namespace dictionaries of all the classes from which derives-- distinction that can matter in the metaclass model we'll meet later in this and focus on in where classes may acquire behavior differently the instancehoweveris omitted by built-inssearch why the lookup changeyou can find formal rationales for this change elsewherethis book is disinclined to parrot justifications for change that breaks many working programs but this is imagined as both an optimization path and solution to seemingly obscure call pattern issue the former rationale is supported by the frequency of built-in operations if every +for examplerequires extra steps at the instanceit can degrade program speed --especially so given the new-style model' many attribute-level extensions new-style class changes |
1,546 | reflects conundrum introduced by the metaclass model because classes are now instances of metaclassesand because metaclasses can define built-in operator methods to process the classes they generatea method call run for class must skip the class itself and look one level higher to pick up method that processes the classrather than selecting the class' own version its own version would result in an unbound method callbecause the class' own method processes lower instances this is just the usual unbound method model we discussed in the prior but is potentially aggravated by the fact that classes can acquire type behavior from metaclasses too as resultbecause classes are both types and instances in their own rightall instances are skipped for built-in operation method lookup this is supposedly applied to normal instances for uniformity and consistencybut both non-built-in names and direct and explicit calls to built-in names still check the instance anyhow though perhaps consequence of the new-style class modelto some this may seem solution arrived at for the sake of usage pattern that was more artificial and obscure than the widely used one it broke its role as optimization path seems more defensiblebut also not without repercussions in particularthis has potentially broad implications for the delegation-based classesoften known as proxy classeswhen embedded objects implement operator overloading in new-style classessuch proxy object' class must generally redefine any such names to catch and delegateeither manually or with tools the net effect is to either significantly complicate or wholly obviate an entire category of programs we explored delegation in and it' common pattern used to augment or adapt another class' interface--to add validationtracingtimingand many other sorts of logic though proxies may be more the exception than the rule in typical python codemany python programs depend upon them implications for attribute interception in simple termsand run in python to show how new-style classes differindexing and prints are routed to __getattr__ in traditional classesbut not for new-style classeswhere printing uses default: class cdata 'spamdef __getattr__(selfname)print(namereturn getattr(self datanameclassic in xcatches built-ins ( [ __getitem__ as of this interaction listingsi've started omitting some blank lines and shortening some hex addresses to bits in object displaysto reduce size and clutter ' going to assume that by this point in the bookyou'll find such small details irrelevant advanced class topics |
1,547 | print(x__str__ spam class (object)rest of class unchanged classic doesn' inherit default new-style in and (built-ins not routed to getattr [ typeerror'cobject does not support indexing print(xthough apparently rationalized in the name of class metaclass methods and optimizing built-in operationsthis divergence is not addressed by special-casing normal instances having __getattr__and applies only to built-in operations--not to normally named methodsor explicit calls to built-in methods by nameclass cpass ( normal lambda normal( __add__ lambda( ) __add__( classic class class (object)pass / new-style class ( normal lambda normal(normals still from instance __add__ lambda( ) __add__( ditto for explicit built-in names typeerrorunsupported operand type(sfor +'cand 'intthis behavior winds up being inherited by the __getattr__ attribute interception methodclass (object)def __getattr__(selfname)print(namex ( normal normal names are still routed to getattr normal __add__ direct calls by name are toobut expressions are not__add__ typeerrorunsupported operand type(sfor +'cand 'intnew-style class changes |
1,548 | in more realistic delegation scenariothis means that built-in operations like expressions no longer work the same as their traditional direct-call equivalent asymmetricallydirect calls to built-in method names still workbut equivalent expressions do not because through-type calls fail for names not at the class level and above in other wordsthis distinction arises in built-in operations onlyexplicit fetches run correctlyclass (object)data 'spamdef __getattr__(selfname)print('getattrnamereturn getattr(self datanamex ( __getitem__( getattr__getitem__ 'ptraditional mapping works but new-style' does not [ typeerror'cobject does not support indexing type(x__getitem__( attributeerrortype object 'chas no attribute '__getitem__x __add__('eggs'getattr__add__ 'spameggsditto for +instance skipped for expression only 'eggstypeerrorunsupported operand type(sfor +'cand 'strtype(x__add__( 'eggs'attributeerrortype object 'chas no attribute '__add__the net effectto code proxy of an object whose interface may in part be invoked by built-in operationsnew-style classes require both __getattr__ for normal namesas well as method redefinitions for all names accessed by built-in operations--whether coded manuallyobtained from superclassesor generated by tools when redefinitions are so incorporatedcalls through both instances and types are equivalent to built-in operationsthough redefined names are no longer routed to the generic __getattr__ undefined name handlereven for explicit name callsclass (object)new-style and data 'spamdef __getattr__(selfname)catch normal names print('getattrnamereturn getattr(self datanamedef __getitem__(selfi)redefine built-ins print('getitemstr( )return self data[irun expr or getattr def __add__(selfother)print('addotherreturn getattr(self data'__add__')(otherx ( advanced class topics |
1,549 | getattrupper upper(getattrupper 'spamx[ getitem 'px __getitem__( getitem 'ptype(x__getitem__( getitem 'px 'eggsaddeggs 'spameggsx __add__('eggs'addeggs 'spameggstype(x__add__( 'eggs'addeggs 'spameggsbuilt-in operation (implicittraditional equivalence (explicitnew-style equivalence ditto for and others for more details we will revisit this change in on metaclassesand by example in the contexts of attribute management in and privacy decorators in in the latter of thesewe'll also explore coding structures for providing proxies with the required operator methods generically--it' not an impossible taskand may need to be coded just once if done well for more of the sort of code influenced by this issuesee those later as well as the earlier examples in and because we'll expand on this issue later in the bookwe'll cut the coverage short here for external links and pointers on this issuethoughsee the following (along with your local search engine)python issue this issue has been discussed widelybut its most official history seems to be documented at was raised as concern for real programs and escalated to be addressedbut proposed library remedy or broader change in python was struck down in favor of simple documentation change to describe the new mandated behavior tool recipesalso see python recipe that describes tool that automatically fills in special method names as generic call dispatchers in proxy class created with metaclass techniques introduced later in this this tool still must ask you to pass in the operator new-style class changes |
1,550 | components of wrapped object may be inherited from arbitrary sourcesother approachesa web search today will uncover numerous additional tools that similarly populate proxy classes with overloading methodsit' widespread concernagainin we'll also see how to code straightforward and general superclasses once that provide the required methods or attributes as mix-inswithout metaclassesredundant code generationor similarly complex techniques this story may evolve over timeof coursebut has been an issue for many years as this stands todayclassic class proxies for objects that do any operator overloading are effectively broken as new-style classes such classes in both and require coding or generating wrappers for all the implicitly invoked operator methods wrapped object may support this is not ideal for such programs--some proxies may require dozens of wrapper methods (potentially over !)--but reflectsor is at least an artifact ofthe design goals of new-style class developers be sure to see ' metaclass coverage for an additional illustration of this issue and its rationale we'll also see there that this behavior of built-ins qualifies as special case in new-style inheritance understanding this well requires more background on metaclasses than the current can providea regrettable byproduct of metaclasses in general--they've become prerequisite to more usage than their originators may have foreseen type model changes on to our next new-style changedepending on your assessmentin new-style classes the distinction between type and class has either been greatly muted or has vanished entirely specificallyclasses are types the type object generates classes as its instancesand classes generate instances of themselves both are considered typesbecause they generate instances in factthere is no real difference between built-in types like lists and strings and userdefined types coded as classes this is why we can subclass built-in typesas shown earlier in this - subclass of built-in type such as list qualifies as newstyle class and becomes new user-defined type types are classes new class-generating types may be coded in python as the metaclasses we'll meet later in this -user-defined type subclasses that are coded with normal class statementsand control creation of the classes that are their instances as we'll seemetaclasses are both class and typethough they are distinct enough to support reasonable argument that the prior type/class dichotomy has become one of metaclass/classperhaps at the cost of added complexity in normal classes advanced class topics |
1,551 | practical contexts where this type/class merging becomes most obvious is when we do explicit type testing with python ' classic classesthe type of class instance is generic "instance,but the types of built-in objects are more specificc:\codec:\python \python class cpass classic classes in (instances are made from classes type( ) __class__ (type(cbut classes are not the same as types __class__ attributeerrorclass has no attribute '__class__type([ ])[ __class__ (type(list)list __class__ (but with new-style classes in xthe type of class instance is the class it' created fromsince classes are simply user-defined types--the type of an instance is its classand the type of user-defined class is the same as the type of built-in object type classes have __class__ attribute nowtoobecause they are instances of typec:\codec:\python \python class (object)pass new-style classes in (type of instance is class it' made from type( ) __class__ (type( ) __class__ (classes are user-defined types the same is true for all classes in python xsince all classes are automatically newstyleeven if they have no explicit superclasses in factthe distinction between builtin types and user-defined class types seems to melt away altogether in xc:\codec:\python \python class cpass (all classes are new-style in type( ) __class__ type of instance is class it' made from (type( ) __class__ (class is typeand type is class type([ ])[ __class__ (new-style class changes |
1,552 | (classes and built-in types work the same as you can seein classes are typesbut types are also classes technicallyeach class is generated by metaclass-- class that is normally either type itselfor subclass of it customized to augment or manage generated classes besides impacting code that does type testingthis turns out to be an important hook for tool developers we'll talk more about metaclasses later in this and again in more detail in implications for type testing besides providing for built-in type customization and metaclass hooksthe merging of classes and types in the new-style class model can impact code that does type testing in python xfor examplethe types of class instances compare directly and meaningfullyand in the same way as built-in type objects this follows from the fact that classes are now typesand an instance' type is the instance' classc:\codec:\python \python class cpass class dpass cd () (type( =type(dfalse xcompares the instancesclasses type( )type( ( __class__d __class__ ( () (type( =type( true with classic classes in xthoughcomparing instance types is almost uselessbecause all instances have the same "instancetype to truly compare typesthe instance __class__ attributes must be compared (if you care about portabilitythis works in xtoobut it' not required there) :\codec:\python \python class cpass class dpass cd () (type( =type(dtrue __class__ = __class__ false xall instances are same typecompare classes explicitly if needed type( )type( ( __class__d __class__ ( advanced class topics |
1,553 | in in this regard--comparing instance types compares the instancesclasses automaticallyc:\codec:\python \python class (object)pass class (object)pass cd () (type( =type(dfalse new-stylesame as all in type( )type( ( __class__d __class__ (of courseas 've pointed out numerous times in this booktype checking is usually the wrong thing to do in python programs (we code to object interfacesnot object types)and the more general isinstance built-in is more likely what you'll want to use in the rare cases where instance class types must be queried howeverknowledge of python' type model can help clarify the class model in general all classes derive from "objectanother ramification of the type change in the new-style class model is that because all classes derive (inheritfrom the class object either implicitly or explicitlyand because all types are now classesevery object derives from the object built-in classwhether directly or through superclass consider the following interaction in python xclass cpass for new-style classes (type( )type(ctype is class instance was created from (as beforethe type of class instance is the class it was made fromand the type of class is the type class because classes and types have merged it is also truethoughthat the instance and class are both derived from the built-in object class and typean implicit or explicit superclass of every classisinstance(xobjecttrue isinstance(cobjecttrue classes always inherit from object the preceding returns the same results for both new-style and classic classes in todaythough type results differ more importantlyas we'll see aheadobject is not added to or present in classic class' __bases__ tupleand so is not true superclass new-style class changes |
1,554 | are classes in the new-style model--built-in types are now classesand their instances derive from objecttootype('spam')type(str(isinstance('spam'objecttrue isinstance(strobjecttrue same for built-in types (classesin facttype itself derives from objectand object derives from typeeven though the two are different objects-- circular relationship that caps the object model and stems from the fact that types are classes that generate classestype(typetype(objectall classes are typesand vice versa isinstance(typeobjecttrue isinstance(objecttypetrue type is object false all classes derive from objecteven type types make classesand type is class implications for defaults the preceding may seem obscurebut this model has number of practical implications for one thingit means that we sometimes must be aware of the method defaults that come with the explicit or implicit object root class in new-style classes onlyc:\codepy - dir(object['__class__''__delattr__''__doc__''__format__''__getattribute__''__hash__'__init__''__new__''__reduce__''__reduce_ex__''__repr__''__setattr__'__sizeof__''__str__''__subclasshook__'class cpass __bases__ classic classes do not inherit from object ( ( __repr__ attributeerrorc instance has no attribute '__repr__class (object)pass new-style classes inherit object defaults __bases__ (, ( __repr__ :\codepy - advanced class topics |
1,555 | this means all classes get defaults in __bases__ (, (__repr__ this model also makes for fewer special cases than the prior type/class distinction of classic classesand it allows us to write code that can safely assume and use an object superclass ( by assuming it as an "anchorin some super built-in roles described aheadand by passing it method calls to invoke default behaviorwe'll see examples of the latter later in the bookfor nowlet' move on to explore the last major new-style change diamond inheritance change our final new-style class model change is also one of its most visibleits slightly different inheritance search order for so-called diamond pattern multiple inheritance trees-- tree pattern in which more than one superclass leads to the same higher superclass further above (and whose name comes from the diamond shape of the tree if you sketch out-- square resting on one of its cornersthe diamond pattern is fairly advanced design conceptonly occurs in multiple inheritance treesand tends to be coded rarely in python practiceso we won' cover this topic in full depth in shortthoughthe differing search orders were introduced briefly in the prior multiple inheritance coveragefor classic classes (the default in )dflr the inheritance search path is strictly depth firstand then left to right--python climbs all the way to the tophugging the left side of the treebefore it backs up and begins to look further to the right this search order is known as dflr for the first letters in its path' directions for new-style classes (optional in and automatic in )mro the inheritance search path is more breadth-first in diamond cases--python first looks in any superclasses to the right of the one just searched before ascending to the common superclass at the top in other wordsthis search proceeds across by levels before moving up this search order is called the new-style mro for "method resolution order(and often just mro for short when used in contrast with the dflr orderdespite the namethis is used for all attributes in pythonnot just methods the new-style mro algorithm is bit more complex than just described--and we'll expand on it bit more formally later--but this is as much as many programmers need to know stillit has both important benefits for new-style class codeas well as program-breaking potential for existing classic class code for examplethe new-style mro allows lower superclasses to overload attributes of higher superclassesregardless of the sort of multiple inheritance trees they are mixed new-style class changes |
1,556 | once when it is accessible from multiple subclasses it' arguably better than dflrbut applies to small subset of python user codeas we'll seethoughthe new-style class model itself makes diamonds much more commonand the mro more important at the same timethe new mro will locate attributes differentlycreating potential incompatibility for classic classes let' move on to some code to see how its differences pan out in practice implications for diamond inheritance trees to illustrate how the new-style mro search differsconsider this simplistic incarnation of the diamond multiple inheritance pattern for classic classes hered' superclasses and both lead to the same common ancestoraclass aattr class ( )pass class ( )attr class (bc)pass ( attr classic (python xb and both lead to tries before searches xdba the attribute attr here is found in superclass abecause with classic classesthe inheritance search climbs as high as it can before backing up and moving right the full dflr search order would visit xdbacand then for this attributethe search stops as soon as attr is found in aabove howeverwith new-style classes derived from built-in like object (and all classes in )the search order is differentpython looks in to the right of bbefore trying above the full mro search order would visit xdbcand then for this attributethe search stops as soon as attr is found in cclass (object)attr class ( )pass class ( )attr class (bc)pass ( attr new-style ("objectnot required in xtries before searches xdbc this change in the inheritance search procedure is based upon the assumption that if you mix in lower in the treeyou probably intend to grab its attributes in preference to ' it also assumes that is always intended to override ' attributes in all contextswhich is probably true when it' used standalone but may not be when it' mixed into diamond with classic classes--you might not even know that may be mixed in like this when you code it advanced class topics |
1,557 | thoughnew-style classes visit first otherwisec could be essentially pointless in diamond context for any names in too--it could not customize and would be used only for names unique to explicit conflict resolution of coursethe problem with assumptions is that they assume thingsif this search order deviation seems too subtle to rememberor if you want more control over the search processyou can always force the selection of an attribute from anywhere in the tree by assigning or otherwise naming the one you want at the place where the classes are mixed together the followingfor examplechooses new-style order in classic class by resolving the choice explicitlyclass aattr class ( )pass class ( )attr class (bc)attr attr ( attr classic <=choose cto the right works like new-style (all xherea tree of classic classes is emulating the search order of new-style classes for specific attributethe assignment to the attribute in picks the version in cthereby subverting the normal inheritance search path ( attr will be lowest in the treenewstyle classes can similarly emulate classic classes by choosing the higher version of the target attribute at the place where the classes are mixed togetherclass (object)attr class ( )pass class ( )attr class (bc)attr attr ( attr new-style <=choose attrabove works like classic (default xif you are willing to always resolve conflicts like thisyou may be able to largely ignore the search order difference and not rely on assumptions about what you meant when you coded your classes naturallyattributes picked this way can also be method functions--methods are normalassignable attributes that happen to reference callable function objectsclass adef meth( )print(' meth'class ( )def meth( )print(' meth'class ( )new-style class changes |
1,558 | class (bc)pass ( meth( meth use default search order will vary per class type defaults to classic order in class (bc)meth meth ( meth( meth <=pick ' methodnew-style (and xclass (bc)meth meth ( meth( meth <=pick ' methodclassic herewe select methods by explicitly assigning to names lower in the tree we might also simply call the desired class explicitlyin practicethis pattern might be more commonespecially for things like constructorsclass (bc)def meth(self) meth(selfredefine lower <=pick ' method by calling such selections by assignment or call at mix-in points can effectively insulate your code from this difference in class flavors this applies only to the attributes you handle this wayof coursebut explicitly resolving the conflicts ensures that your code won' vary per python versionat least in terms of attribute conflict selection in other wordsthis can serve as portability technique for classes that may need to be run under both the new-style and classic class models explicit is better than implicit--for method resolution tooeven without the classic/new-style class divergencethe explicit method resolution technique shown here may come in handy in multiple inheritance scenarios in general for instanceif you want part of superclass on the left and part of superclass on the rightyou might need to tell python which same-named attributes to choose by using explicit assignments or calls in subclasses we'll revisit this notion in "gotchaat the end of this also note that diamond inheritance patterns might be more problematic in some cases than 've implied here ( what if and both have required constructors that call to the constructor in ?since such contexts are rare in real-world pythonwe'll defer this topic until we explore the super built-in function near the end of this besides providing generic access to superclasses in single inheritance treessuper supports cooperative mode for resolving conflicts in multiple inheritance trees by ordering method calls per the mro--assuming this order makes sense in this context too advanced class topics |
1,559 | in sumby defaultthe diamond pattern is searched differently for classic and new-style classesand this is non-backward-compatible change keep in mindthoughthat this change primarily affects diamond pattern cases of multiple inheritancenew-style class inheritance works the same for most other inheritance tree structures furtherit' not impossible that this entire issue may be of more theoretical than practical importance --because the new-style search wasn' significant enough to address until python and didn' become standard until it seems unlikely to impact most python code having said thati should also note that even though you might not code diamond patterns in classes you write yourselfbecause the implied object superclass is above every root class in as we saw earlierevery case of multiple inheritance exhibits the diamond pattern today that isin new-style classesobject automatically plays the role that the class does in the example we just considered hence the new-style mro search rule not only modifies logical semanticsbut is also an important performance optimization--it avoids visiting and searching the same class more than onceeven the automatic object just as importantwe've also seen that the implied object superclass in the new-style model provides default methods for variety of built-in operationsincluding the __str__ and __repr__ display format methods run dir(objectto see which methods are provided without the new-style mro search orderin multiple inheritance cases the defaults in object would always override redefinitions in user-coded classesunless they were always made in the leftmost superclass in other wordsthe new-style class model itself makes using the new-style search order more criticalfor more visual example of the implied object superclass in xand other examples of diamond patterns created by itsee the listtree class' output in the lister py example in the preceding as well as the classtree py tree walker example in -and the next section more on the mromethod resolution order to trace how new-style inheritance works by defaultwe can also use the new class __mro__ attribute mentioned in the preceding class lister examples-technically new-style extensionbut useful here to explore change this attribute returns class' mro--the order in which inheritance searches classes in new-style class tree this mro is based on the superclass linearization algorithm initially developed in the dylan programming languagebut later adopted by other languages including python and perl the mro algorithm this book avoids full description of the mro algorithm deliberatelybecause many python programmers don' need to care (this only impacts diamondswhich are relanew-style class changes |
1,560 | details of the mro are bit too arcane and academic for this text as rulethis book avoids formal algorithms and prefers to teach informally by example on the other handsome readers may still have an interest in the formal theory behind new-style mro if this set includes youit' described in full detail onlinesearch python' manuals and the web for current mro links in shortthoughthe mro essentially works like this list all the classes that an instance inherits from using the classic class' dflr lookup ruleand include class multiple times if it' visited more than once scan the resulting list for duplicate classesremoving all but the last occurrence of duplicates in the list the resulting mro list for given class includes the classits superclassesand all higher superclasses up to the object root class at the top of the tree it' ordered such that each class appears before its parentsand multiple parents retain the order in which they appear in the __bases__ superclass tuple cruciallythoughbecause common parents in diamonds appear only at the position of their last visitationlower classes are searched first when the mro list is later used by attribute inheritance moreovereach class is included and thus visited just onceno matter how many classes lead to it we'll see applications of this algorithm later in this including that in super- built-in that elevates the mro to required reading if you wish to fully understand how methods are dispatched by this callshould you choose to use it as we'll seedespite its namethis call invokes the next class on the mrowhich might not be superclass at all tracing the mro if you just want to see how python' new-style inheritance orders superclasses in generalthoughnew-style classes (and hence all classes in xhave class __mro__ attributewhich is tuple giving the linear search order python uses to look up attributes in superclasses reallythis attribute is the inheritance order in new-style classesand is often as much mro detail as many python users need here are some illustrative examplesrun in xfor diamond inheritance patterns onlythe search is the new order we've been studying--across before upper the mro for new-style classes always used in xand available as an option in xclass apass class ( )pass diamondsorder differs for newstyle class ( )pass breadth-first across lower levels class (bc)pass __mro__ ( advanced class topics |
1,561 | object root)--to the topand then to the right ( dflrdepth first and left to rightthe model used for all classic classes in )class apass class ( )pass nondiamondsorder same as classic class cpass depth firstthen left to right class (bc)pass __mro__ (the mro of the following treefor exampleis the same as the earlier diamondper dflrclass apass class bpass another nondiamonddflr class ( )pass class (bc)pass __mro__ (notice how the implied object superclass always shows up at the end of the mroas we've seenit' added automatically above root (topmostclasses in new-style class trees in (and optionally in ) __bases__ superclass linksobject at two roots (, __bases__ (, __bases__ (, __bases__ (technicallythe implied object superclass always creates diamond in multiple inheritance even if your classes do not--your classes are searched as beforebut the newstyle mro ensures that object is visited lastso your classes can override its defaultsclass xpass class ypass class ( )pass nondiamonddepth first then left to right class ( )pass though implied "objectalways forms diamond class (ab)pass mro([ __bases__y __bases__ ((,)(,) __bases__b __bases__ ((,)(,)new-style class changes |
1,562 | unless classes derive from object strictly speakingnew-style classes also have class mro(method used in the prior example for varietyit' called at class instantiation time and its return value is list used to initialize the __mro__ attribute when the class is created (the method is available for customization in metaclassesdescribed lateryou can also select mro names if classesobject displays are too detailedthough this book usually shows the objects to remind you of their true formd mro(=list( __mro__true [cls __name__ for cls in __mro__[' '' '' '' '' ''object'however you access or display themclass mro paths might be useful to resolve confusionand in tools that must imitate python' inheritance search order the next section shows the latter role in action examplemapping attributes to inheritance sources as prime mro use casewe noted at the end of the prior that class tree climbers--such as the class tree lister mix-in we wrote there--might benefit from the mro as codedthe tree lister gave the physical locations of attributes in class tree howeverby mapping the list of inherited attributes in dir result to the linear mro sequence (or dflr order for classic classes)such tools can more directly associate attributes with the classes from which they are inherited--also useful relationship for programmers we won' recode our tree lister herebut as first major stepthe following filemapattrs pyimplements tools that can be used to associate attributes with their inheritance sourceas an added bonusits mapattrs function demonstrates how inheritance actually searches for attributes in class tree objectsthough the new-style mro is largely automated for us""file mapattrs py ( xmain toolmapattrs(maps all attributes on or inherited by an instance to the instance or class from which they are inherited assumes dir(gives all attributes of an instance to simulate inheritanceuses either the class' mro tuplewhich gives the search order for new-style classes (and all in )or recursive traversal to infer the dflr order of classic classes in also hereinheritance(gives version-neutral class orderingassorted dictionary tools using / comprehensions ""import pprint def trace(xlabel=''end='\ ') advanced class topics |
1,563 | def filterdictvals(dv)""dict with entries for value removed filterdictvals(dict( = = = ) ={' ' ""return {kv for (kv in items(if !vdef invertdict( )""dict with values changed to keys (grouped by valuesvalues must all be hashable to work as dict/set keys invertdict(dict( = = = )={ [' '' '] [' ']""def keysof( )return sorted( for in keys(if [ =vreturn {vkeysof(vfor in set( values())def dflr(cls)""classic depth-first left-to-right order of class tree at cls cycles not possiblepython disallows on __bases__ changes ""here [clsfor sup in cls __bases__here +dflr(supreturn here def inheritance(instance)""inheritance order sequencenew-style (mroor classic (dflr""if hasattr(instance __class__'__mro__')return (instance,instance __class__ __mro__ elsereturn [instancedflr(instance __class__def mapattrs(instancewithobject=falsebysource=false)""dict with keys giving all inherited attributes of instancewith values giving the object that each is inherited from withobjectfalse=remove object built-in class attributes bysourcetrue=group result by objects instead of attributes supports classes with slots that preclude __dict__ in instances ""attr obj {inherits inheritance(instancefor attr in dir(instance)for obj in inheritsif hasattr(obj'__dict__'and attr in obj __dict__attr obj[attrobj break see slots if not withobjectnew-style class changes |
1,564 | return attr obj if not bysource else invertdict(attr objif __name__ ='__main__'print('classic classes in xnew-style in 'class aattr class ( )attr class ( )attr class (bc)pass (print('py=>%si attr python' search =ourstrace(inheritance( )'inh\ '[inheritance ordertrace(mapattrs( )'attrs\ 'attrs =source trace(mapattrs(ibysource=true)'objs\ 'source =[attrsprint('new-style classes in and 'class (object)attr class ( )attr class ( )attr class (bc)pass (print('py=>%si attr trace(inheritance( )'inh\ 'trace(mapattrs( )'attrs\ 'trace(mapattrs(ibysource=true)'objs\ '"(object)optional in this file assumes dir gives all an instance' attributes it maps each attribute in dir result to its source by scanning either the mro order for new-style classesor the dflr order for classic classessearching each object' namespace __dict__ along the way for classic classesthe dflr order is computed with simple recursive scan the net effect is to simulate python' inheritance search in both class models this file' self-test code applies its tools to the diamond multiple-inheritance trees we saw earlier it uses python' pprint library module to display lists and dictionaries nicely --pprint pprint is its basic calland its pformat returns print string run this on python to see both classic dflr and new-style mro search orderson python the object derivation is unnecessaryand both tests give the samenew-style results importantlyattr whose value is labeled with "py=>and whose name appears in the results listsis inherited from class in classic searchbut from class in new-style searchc:\codepy - mapattrs py classic classes in xnew-style in py=> inh [attrs advanced class topics |
1,565 | '__module__''attr ''attr 'objs {['attr ']['attr ']['__doc__''__module__']new-style classes in and py=> inh (attrs {'__dict__''__doc__''__module__''__weakref__''attr ''attr 'objs {['__dict__''__weakref__']['attr ']['attr ']['__doc__''__module__']as larger application of these toolsthe following is our inheritance simulator at work in on the preceding testmixin py file' test classes ( 've deleted some builtin names here for spaceas usualrun live for the whole listnotice how __x pseudoprivate names are mapped to their defining classesand how listinstance appears in the mro before objectwhich has __str__ that would otherwise be chosen first--as you'll recallmixing this method in was the whole point of the lister classesc:\codepy - from mapattrs import tracedflrinheritancemapattrs from testmixin import sub sub(sub inherits from super and listinstance roots trace(dflr( __class__) search orderimplied object before lister[trace(inheritance( ) ( newstylesearch orderlister first (new-style class changes |
1,566 | trace(mapattrs( ){'_listinstance__attrnames''__init__''__str__'etc 'data ''data ''data ''ham''spam'trace(mapattrs(ibysource=true){['data ''data ''data ']['_listinstance__attrnames''__str__']['__dict__''__weakref__''ham']['__doc__''__init__''__module__''__qualname__''spam']trace(mapattrs(iwithobject=true){'_listinstance__attrnames''__class__''__delattr__'etc here' the bit you might run if you want to label class objects with names inherited by an instancethough you may want to filter out some built-in double-underscore names for the sake of userseyesightamap mapattrs(iwithobject=truebysource=truetrace(amap{['data ''data ''data ']['_listinstance__attrnames''__str__']['__dict__''__weakref__''ham']['__doc__''__init__''__module__''__qualname__''spam']['__class__''__delattr__'etc '__sizeof__''__subclasshook__']finallyand as both follow-up to the prior ruminations and segue to the next section herethe following shows how this scheme works for class-based slots attributes too because class' __dict__ includes both normal class attributes and individual entries for the instance attributes defined by its __slots__ listthe slots at advanced class topics |
1,567 | class from which they are acquiredeven though they are not physically stored in the instance' __dict__ itselfmapattrs-slots pytest __slots__ attribute inheritance from mapattrs import mapattrstrace class (object)__slots__ [' '' '] class ( )__slots__ [' '' 'class ( ) class (bc) def __init__(self)self name 'bob' (trace(mapattrs(ibysource=true)alsotrace(mapattrs( )for explicitly new-style classes like those in this filethe results are the same under both and though adds an extra built-in name to the set the attribute names here reflect all those inherited by the instance from user-defined classeseven those implemented by slots defined at classes and stored in space allocated in the instancec:\codepy - mapattrs-slots py {['name'][' ']['__dict__''__doc__''__init__''__module__''__qualname__''__weakref__'' '][' '' ']['__slots__'' '' ']but we need to move ahead to understand the role of slots better--and understand why mapattrs must be careful to check to see if __dict__ is present before fetching itstudy this code for more insight for the prior tree listeryour next step might be to index the mapattrs function' bysource=true dictionary result to obtain an object' attributes during the tree sketch traversalinstead of (or perhaps in addition to?its current physical __dict__ scan you'll probably need to use getattr on the instance to fetch attribute valuesbecause some may be implemented as slots or other "virtualattributes at their source classesand fetching these at the class directly won' return the instance' value if code anymore herethoughi'll deprive readers of the remaining funand the next section of its subject matter new-style class changes |
1,568 | and but appears to have an issue in pythons and where it raises wrong-number-arguments exception internally for the objects displayed here since 've already devoted too much space to covering transitory python defectsand since this has been repaired in the versions of python used in this editionwe'll leave working around this in the suggested exercises column for readers running this on the infected pythonschange trace to simple prints as neededand mind the note on battery dependence in new-style class extensions beyond the changes described in the prior section (some of whichfranklymay seem too academic and obscure to matter to many readers of this book)new-style classes provide handful of more advanced class tools that have more direct and practical application--slotspropertiesdescriptorsand more the following sections provide an overview of each of these additional featuresavailable for new-style class in python and all classes in python also in this extensions category are the __mro__ attribute and the super callboth covered elsewhere--the former in the previous section to explore changeand the latter postponed until end to serve as larger case study slotsattribute declarations by assigning sequence of string attribute names to special __slots__ class attributewe can enable new-style class to both limit the set of legal attributes that instances of the class will haveand optimize memory usage and possibly program speed as we'll findthoughslots should be used only in applications that clearly warrant the added complexity they will complicate your codemay complicate or break code you may useand require universal deployment to be effective slot basics to use slotsassign sequence of string names to the special __slots__ variable and attribute at the top level of class statementonly those names in the __slots__ list can be assigned as instance attributes howeverlike all names in pythoninstance attribute names must still be assigned before they can be referencedeven if they're listed in __slots__class limiter(object)__slots__ ['age''name''job' limiter( age attributeerrorage advanced class topics must assign before use |
1,569 | looks like instance data age ape illegalnot in __slots__ attributeerror'limiterobject has no attribute 'apethis feature is envisioned as both way to catch typo errors like this (assignments to illegal attribute names not in __slots__ are detectedas well as an optimization mechanism allocating namespace dictionary for every instance object can be expensive in terms of memory if many instances are created and only few attributes are required to save spaceinstead of allocating dictionary for each instancepython reserves just enough space in each instance to hold value for each slot attributealong with inherited attributes in the common class to manage slot access this might additionally speed executionthough this benefit is less clear and might vary per programplatformand python slots are also something of major break with python' core dynamic naturewhich dictates that any name may be created by assignment in factthey imitate +for efficiency at the expense of flexibilityand even have the potential to break some programs as we'll seeslots also come with plethora of special-case usage rules per python' own manualthey should not be used except in clearly warranted cases--they are difficult to use correctlyand areto quote the manualbest reserved for rare cases where there are large numbers of instances in memorycritical application in other wordsthis is yet another feature that should be used only if clearly warranted unfortunatelyslots seem to be showing up in python code much more often than they shouldtheir obscurity seems to be draw in itself as usualknowledge is your best ally in such thingsso let' take quick look here in python non-slots attribute space requirements have been reduced with key-sharing dictionary modelwhere the __dict__ dictionaries used for objectsattributes may share part of their internal storageincluding that of their keys this may lessen some of the value of __slots__ as an optimization toolper benchmark reportsthis change reduces memory use by to for object-oriented programsgives small improvement in speed for programs that create many similar objectsand may be optimized further in the future on the other handthis won' negate the presence of __slots__ in existing code you may need to understandslots and namespace dictionaries potential benefits asideslots can complicate the class model--and code that relies on it--substantially in factsome instances with slots may not have __dict__ attribute new-style class extensions |
1,570 | does not include to be clearthis is major incompatibility with the traditional class model--one that can complicate any code that accesses attributes genericallyand may even cause some programs to fail altogether for instanceprograms that list or access instance attributes by name string may need to use more storage-neutral interfaces than __dict__ if slots may be used because an instance' data may include class-level names such as slots--either in addition to or instead of namespace dictionary storage--both attribute sources may need to be queried for completeness let' see what this means in terms of codeand explore more about slots along the way first offwhen slots are usedinstances do not normally have an attribute dictionary --insteadpython uses the class descriptors feature introduced ahead to allocate and manage space reserved for slot attributes in the instance in python xand in for new-style classes derived from objectclass c__slots__ [' '' 'requires "(object)in only __slots__ means no __dict__ by default ( __dict__ attributeerror'cobject has no attribute '__dict__howeverwe can still fetch and set slot-based attributes by name string using storageneutral tools such as getattr and setattr (which look beyond the instance __dict__ and thus include class-level names like slotsand dir (which collects all inherited names throughout class tree)getattr( ' ' setattr( ' ' 'ain dir(xtrue 'bin dir(xtrue but getattr(and setattr(still work and dir(finds slot attributes too also keep in mind that without an attribute namespace dictionaryit' not possible to assign new names to instances that are not names in the slots listclass d__slots__ [' '' 'def __init__(self)self use (objectfor same result in cannot add new names if no __dict__ (attributeerror'dobject has no attribute ' advanced class topics |
1,571 | __slots__in order to create an attribute namespace dictionary tooclass d__slots__ [' '' ''__dict__' def __init__(self)self ( attributeerrora name __dict__ to include one too class attrs work normally stored in __dict__a is slot all instance attrs undefined until assigned in this caseboth storage mechanisms are used this renders __dict__ too limited for code that wishes to treat slots as instance databut generic tools such as getattr still allow us to process both storage forms as single set of attributesx __dict__ some objects have both __dict__ and slot names {' ' getattr(can fetch either type of attr __slots__ [' '' ''__dict__'getattr( ' ')getattr( ' ')getattr( ' 'fetches all forms ( because dir also returns all inherited attributesthoughit might be too broad in some contextsit also includes class-level methodsand even all object defaults code that wishes to list just instance attributes may in principle still need to allow for both storage forms explicitly we might at first naively code this as followsfor attr in list( __dict__x __slots__print(attr'=>'getattr(xattr)wrong since either can be omittedwe may more correctly code this as followsusing get attr to allow for defaults-- noble but nonetheless inaccurate approachas the next section will explainfor attr in list(getattr( '__dict__'[])getattr( '__slots__'[])print(attr'=>'getattr(xattr) = = = __dict__ ={' ' less wrong multiple __slot__ lists in superclasses the preceding code works in this specific casebut in general it' not entirely accurate specificallythis code addresses only slot names in the lowest __slots__ attribute new-style class extensions |
1,572 | isa name' absence in the lowest __slots__ list does not preclude its existence in higher __slots__ because slot names become class-level attributesinstances acquire the union of all slot names anywhere in the treeby the normal inheritance ruleclass e__slots__ [' '' 'class ( )__slots__ [' ''__dict__' ( ax ( superclass has slots but so does its subclass the instance is the union (slotsacinspecting just the inherited slots list won' pick up slots defined higher in class treee __slots__ [' '' ' __slots__ [' ''__dict__' __slots__ [' ''__dict__' __dict__ {' ' but slots are not concatenated instance inherits *lowest__slots__ and has its own an attr dict for attr in list(getattr( '__dict__'[])getattr( '__slots__'[])print(attr'=>'getattr(xattr) = = __dict__ ={' ' other superclass slots misseddir(xbut dir(includes all slot names many names omitted ' '' '' '' 'in other wordsin terms of listing instance attributes genericallyone __slots__ isn' always enough--they are potentially subject to the full inheritance search procedure see the earlier mapattrs-slots py for another example of slots appearing in multiple superclasses if multiple classes in class tree have their own __slots__ attributesgeneric programs must develop other policies for listing attributes--as the next section explains handling slots and other "virtualattributes generically at this pointyou may wish to review the discussion of slots policy options at the coverage of the lister py display mix-in classes near the end of the preceding prime example of why generic programs may need to care about slots such tools that attempt to list instance data attributes generically must account for slotsand perhaps other such "virtualinstance attributes like properties and descriptors discussed ahead --names that similarly reside in classes but may provide attribute values for instances advanced class topics |
1,573 | on request slots are the most data-centric of thesebut are representative of larger category such attributes require inclusive approachesspecial handlingor general avoidance-the latter of which becomes unsatisfactory as soon as any programmer uses slots in subject code reallyclass-level instance attributes like slots probably necessitate redefinition of the term instance data--as locally stored attributesthe union of all inherited attributesor some subset thereof for examplesome programs might classify slot names as attributes of classes instead of instancesthese attributes do not exist in instance namespace dictionariesafter all alternativelyas shown earlierprograms can be more inclusive by relying on dir to fetch all inherited attribute names and getattr to fetch their corresponding values for the instance--without regard to their physical location or implementation if you must support slots as instance datathis is likely the most robust way to proceedclass slotful__slots__ [' '' ''__dict__'def __init__(selfdata)self data slotful( ai ai bi ( normal attribute fetch __dict__ both __dict__ and slots storage {' ' [ for in dir(iif not startswith('__')[' '' '' ' __dict__[' ' getattr( ' ')getattr( ' '( __dict__ is only one attr source dir+getattr is broader than __dict__ applies to slotspropertiesdescrip for in ( for in dir(iif not startswith('__'))print(agetattr(ia) under this dir/getattr modelyou can still map attributes to their inheritance sourcesand filter them more selectively by source or type if neededby scanning the mro-as we did earlier in both mapattrs py and its application to slots in mapattrs-slots py as an added bonussuch tools and policies for handling slots will potentially apply automatically to properties and descriptors toothough these attributes are more explicitly computed valuesand less obviously instance-related data than slots also keep in mind that this is not just tools issue class-based instance attributes like slots also impact the traditional coding of the __setattr__ operator overloading method new-style class extensions |
1,574 | instance __dict__and may even imply its absencenew-style classes must instead generally run attribute assignments by routing them to the object superclass in practicethis may make this method fundamentally different in some classic and new-style classes slot usage rules slot declarations can appear in multiple classes in class treebut when they do they are subject to number of constraints that are somewhat difficult to rationalize unless you understand the implementation of slots as class-level descriptors for each slot name that are inherited by the instances where the managed space is reserved (descriptors are an advanced tool we'll study in detail in the last part of this book)slots in subs are pointless when absent in supersif subclass inherits from superclass without __slots__the instance __dict__ attribute created for the superclass will always be accessiblemaking __slots__ in the subclass largely pointless the subclass still manages its slotsbut doesn' compute their values in any wayand doesn' avoid dictionary--the main reason to use slots slots in supers are pointless when absent in subssimilarlybecause the meaning of __slots__ declaration is limited to the class in which it appearssubclasses will produce an instance __dict__ if they do not define __slots__rendering __slots__ in superclass largely pointless redefinition renders super slots pointlessif class defines the same slot name as superclassits redefinition hides the slot in the superclass per normal inheritance you can access the version of the name defined by the superclass slot only by fetching its descriptor directly from the superclass slots prevent class-level defaultsbecause slots are implemented as class-level descriptors (along with per-instance space)you cannot use class attributes of the same name to provide defaults as you can for normal instance attributesassigning the same name in the class overwrites the slot descriptor slots and __dict__as shown earlier__slots__ preclude both an instance __dict__ and assigning names not listedunless __dict__ is listed explicitly too we've already seen the last of these in actionand the earlier mapattrs-slots py illustrates the third it' easy to demonstrate how the new rules here translate to actual code-most cruciallya namespace dictionary is created when any class in tree omits slotsthereby negating the memory optimization benefitclass cpass class ( )__slots__ [' ' ( __dict__ {' ' __dict__ keys( advanced class topics bullet slots in sub but not super makes instance dict for nonslots but slot name still managed in class |
1,575 | class c__slots__ [' 'class ( )pass ( __dict__ {' ' __dict__ keys(dict_keys(' ''__slots__']bullet slots in super but not sub makes instance dict for nonslots but slot name still managed in class class c__slots__ [' 'class ( )__slots__ [' 'bullet only lowest slot accessible class c__slots__ [' '] bullet no class-level defaults valueerror'ain __slots__ conflicts with class variable in other wordsbesides their program-breaking potentialslots essentially require both universal and careful deployment to be effective--because slots do not compute values dynamically like properties (coming up in the next section)they are largely pointless unless each class in tree uses them and is cautious to define only new slot names not defined by other classes it' an all-or-nothing feature--an unfortunate property shared by the super call discussed aheadclass c__slots__ [' 'assumes universal usediffering names class ( )__slots__ [' ' ( __dict__ attributeerror'dobject has no attribute '__dict__c __dict__ keys() __dict__ keys((dict_keys(' ''__slots__'])dict_keys(' ''__slots__'])such rules--among others regarding weak references omitted here for space--are part of the reason slots are not generally recommendedexcept in pathological cases where their space reduction is significant even thentheir potential to complicate or break code should be ample cause to carefully consider the tradeoffs not only must they be spread almost neurotically throughout frameworkthey may also break tools you rely on example impacts of slotslisttree and mapattrs as more realistic example of slotseffectsdue to the first bullet in the prior section' listtree class does not fail when mixed in to class that defines __slots__even though it scans instance namespace dictionaries the lister class' own lack of slots is enough to ensure that the instance will still have __dict__and hence not trigger an exception when fetched or indexed for exampleboth of the following display without error--the second also allows names not in the slots list to be assigned as instances attributesincluding any required by the superclassclass (listtree)pass (okno __slots__ used new-style class extensions |
1,576 | class (listtree)__slots__ [' '' ' ( print(xoksuperclass produces __dict__ displays at xa and at the following classes display correctly as well--any nonslot class like listtree generates an instance __dict__and can thus safely assume its presenceclass a__slots__ [' 'class (alisttree)pass class a__slots__ [' 'class (alisttree)__slots__ [' 'both ok by bullet above displays at ba at although it renders subclass slots pointlessthis is positive side effect for tools classes like listtree (and its predecessorin generalthoughsome tools might need to catch exceptions when __dict__ is absent or use hasattr or getattr to test or provide defaults if slot usage may preclude namespace dictionary in instance objects inspected for exampleyou should now be able to understand why the mapattrs py program earlier in this must check for the presence of __dict__ before fetching it-instance objects created from classes with __slots__ won' have one in factif we use the highlighted alternative line in the followingthe mapattrs function fails with an exception when attempting to look for an attribute name in the instance at the front of the inheritance path sequencedef mapattrs(instancewithobject=falsebysource=false)for attr in dir(instance)for obj in inheritsif attr in obj __dict__may fail if __slots__ used class c__slots__ [' ' (mapattrs(xattributeerror'cobject has no attribute '__dict__either of the following works around the issueand allows the tool to support slots-the first provides defaultand the second is more verbose but seems marginally more explicit in its intentif attr in getattr(obj'__dict__'{})if hasattr(obj'__dict__'and attr in obj __dict__as mentioned earliersome tools may benefit from mapping dir results to objects in the mro this wayinstead of scanning an instance __dict__ in general--without this more inclusive approachattributes implemented by class-level tools like slots won' be reported as instance data even sothis doesn' necessarily excuse such tools from allowing for missing __dict__ in the instance too advanced class topics |
1,577 | finallywhile slots primarily optimize memory usetheir speed impact is less clear-cut here' simple test script using the timeit techniques we studied in for both the slots and nonslots (instance dictionarystorage modelsit makes , instancesassigns and fetches attributes on eachand repeats , times--for both models taking the best of runs that each exercise total of attribute operationsfile slots-test py from __future__ import print_function import timeit base ""is [for in range( ) ( is append( ""stmt ""class c__slots__ [' '' '' '' '""base print('slots =>'end='print(min(timeit repeat(stmtnumber= repeat= ))stmt ""class cpass ""base print('nonslots=>'end='print(min(timeit repeat(stmtnumber= repeat= ))at least on this codeon my laptopand in my installed versions (python and )the best times imply that slots are slightly quicker in and wash in xthough this says little about memory spaceand is prone to change arbitrarily in the futurec:\codepy - slots-test py slots = nonslots= :\codepy - slots-test py slots = nonslots= for more on slots in generalsee the python standard manual set also watch for the private decorator case study of --an example that naturally allows for attributes based on both __slots__ and __dict__ storageby using delegation and storageneutral accessor tools like getattr new-style class extensions |
1,578 | our next new-style extension is properties-- mechanism that provides another way for new-style classes to define methods called automatically for access or assignment to instance attributes this feature is similar to properties ( "gettersand "setters"in languages like java and #but in python is generally best used sparinglyas way to add accessors to attributes after the fact as needs evolve and warrant where neededthoughproperties allow attribute values to be computed dynamically without requiring method calls at the point of access though properties cannot support generic attribute routing goalsat least for specific attributes they are an alternative to some traditional uses of the __getattr__ and __setattr__ overloading methods we first studied in properties have similar effect to these two methodsbut by contrast incur an extra method call only for accesses to names that require dynamic computation--other nonproperty names are accessed normally with no extra calls although __getattr__ is invoked only for undefined namesthe __setattr__ method is instead called for assignment to every attribute properties and slots are related toobut serve different goals both implement instance attributes that are not physically stored in instance namespace dictionaries-- sort of "virtualattribute--and both are based on the notion of class-level attribute descriptors in contrastslots manage instance storagewhile properties intercept access and compute values arbitrarily because their underlying descriptor implementation tool is too advanced for us to cover hereproperties and descriptors both get full treatment in property basics as brief introductionthougha property is type of object assigned to class attribute name you generate property by calling the property built-in functionpassing in up to three accessor methods--handlers for getsetand delete operations--as well as an optional docstring for the property if any argument is passed as none or omittedthat operation is not supported the resulting property object is typically assigned to name at the top level of class statement ( name=property())and special syntax we'll meet later is available to automate this step when thus assignedlater accesses to the class property name itself as an object attribute ( obj nameare automatically routed to one of the accessor methods passed into the property call for examplewe've seen how the __getattr__ operator overloading method allows classes to intercept undefined attribute references in both classic and new-style classesclass operatorsdef __getattr__(selfname)if name ='age'return else advanced class topics |
1,579 | operators( age name attributeerrorname runs __getattr__ runs __getattr__ here is the same examplecoded with properties insteadnote that properties are available for all classes but require the new-style object derivation in to work properly for intercepting attribute assignments (and won' complain if you forget this--but will silently overwrite your property with the new data!)class properties(object)need object in for setters def getage(self)return age property(getagenonenonenone(getsetdeldocs)or use properties( age runs getage name normal fetch attributeerror'propertiesobject has no attribute 'namefor some coding tasksproperties can be less complex and quicker to run than the traditional techniques for examplewhen we add attribute assignment supportproperties become more attractive--there' less code to typeand no extra method calls are incurred for assignments to attributes we don' wish to compute dynamicallyclass properties(object)need object in for setters def getage(self)return def setage(selfvalue)print('set age%svalueself _age value age property(getagesetagenonenonex properties( age age set age _age age job 'trainerx job 'trainerruns getage runs setage normal fetchno getage call runs getage normal assignno setage call normal fetchno getage call the equivalent class based on operator overloading incurs extra method calls for assignments to attributes not being managed and needs to route attribute assignments through the attribute dictionary to avoid loops (orfor new-style classesto the new-style class extensions |
1,580 | properties coded in other classes)class operatorsdef __getattr__(selfname)if name ='age'return elseraise attributeerror(namedef __setattr__(selfnamevalue)print('set% % (namevalue)if name ='age'self __dict__['_age'value elseself __dict__[namevalue operators( age age setage _age age job 'trainersetjob trainer job 'traineron undefined reference on all assignments or object __setattr__(runs __getattr__ runs __setattr__ definedno __getattr__ call runs __getattr__ runs __setattr__ again definedno __getattr__ call properties seem like win for this simple example howeversome applications of __getattr__ and __setattr__ still require more dynamic or generic interfaces than properties directly provide for examplein many cases the set of attributes to be supported cannot be determined when the class is codedand may not even exist in any tangible form ( when delegating arbitrary attribute references to wrapped/embedded object genericallyin such contextsa generic __getattr__ or __setattr__ attribute handler with passedin attribute name is usually preferable because such generic handlers can also support simpler casesproperties are often an optional and redundant extension--albeit one that may avoid extra calls on assignmentsand one that some programmers may prefer when applicable for more details on both optionsstay tuned for in the final part of this book as we'll see thereit' also possible to code properties using the symbol function decorator syntax-- topic introduced later in this and an equivalent and automatic alternative to manual assignment in the class scopeclass properties(object)@property def age(self)@age setter advanced class topics coding properties with decoratorsahead |
1,581 | to make sense of this decorator syntaxthoughwe must move ahead __getattribute__ and descriptorsattribute tools also in the class extensions departmentthe __getattribute__ operator overloading methodavailable for new-style classes onlyallows class to intercept all attribute referencesnot just undefined references this makes it more potent than its __get attr__ cousin we used in the prior sectionbut also trickier to use--it' prone to loops much like __setattr__but in different ways for more specialized attribute interception goalsin addition to properties and operator overloading methodspython supports the notion of attribute descriptors--classes with __get__ and __set__ methodsassigned to class attributes and inherited by instancesthat intercept read and write accesses to specific attributes as previewhere' one of the simplest descriptors you're likely to encounterclass agedesc(object)def __get__(selfinstanceowner)return def __set__(selfinstancevalue)instance _age value class descriptors(object)age agedesc( descriptors( age age _age runs agedesc __get__ runs agedesc __set__ normal fetchno agedesc call descriptors have access to state in instances of themselves as well as their client classand are in sense more general form of propertiesin factproperties are simplified way to define specific type of descriptor--one that runs functions on access descriptors are also used to implement the slots feature we met earlierand other python tools because __getattribute__ and descriptors are too substantial to cover well herewe'll defer the rest of their coverageas well as much more on propertiesto in the final part of this book we'll also employ them in examples in and study how they factor into inheritance in other class changes and extensions as mentionedwe're also postponing coverage of the super built-in--an additional major new-style class extension that relies on its mro--until the end of this before we get therethoughwe're going to explore additional class-related changes new-style class extensions |
1,582 | at roughly the same timestatic and class methodsdecoratorsand more many of the changes and feature additions of new-style classes integrate with the notion of subclassable types mentioned earlier in this because subclassable types and new-style classes were introduced in conjunction with merging of the type/class dichotomy in python and beyond as we've seenin xthis merging is completeclasses are now typesand types are classesand python classes today still reflect both that conceptual merging and its implementation along with these changespython also grew more coherent and generalized protocol for coding metaclasses--classes that subclass the type objectintercept class creation callsand may provide behavior acquired by classes accordinglythey provide welldefined hook for management and augmentation of class objects they are also an advanced topic that is optional for most python programmersso we'll postpone further details here we'll glimpse metaclasses again later in this in conjunction with class decorators-- feature whose roles often overlap--but we'll postpone their full coverage until in the final part of this book for our purpose herelet' move on to handful of additional class-related extensions static and class methods as of python it is possible to define two kinds of methods within class that can be called without an instancestatic methods work roughly like simple instance-less functions inside classand class methods are passed class instead of an instance both are similar to tools in other languages ( +static methodsalthough this feature was added in conjunction with the new-style classes discussed in the prior sectionsstatic and class methods work for classic classes too to enable these method modesyou must call special built-in functions named staticmethod and classmethod within the classor invoke them with the special @name decoration syntax we'll meet later in this these functions are required to enable these special method modes in python xand are generally needed in in python xa staticmethod declaration is not required for instance-less methods called only through class namebut is still required if such methods are called through instances why the special methodsas we've learneda class' method is normally passed an instance object in its first argumentto serve as the implied subject of the method call--that' the "objectin "object-oriented programming todaythoughthere are two ways to modify this model before explain what they arei should explain why this might matter to you sometimesprograms need to process data associated with classes instead of instances consider keeping track of the number of instances created from classor maintaining advanced class topics |
1,583 | and its processing are associated with the class rather than its instances that isthe information is usually stored on the class itself and processed apart from any instance for such taskssimple functions coded outside class can often suffice--because they can access class attributes through the class namethey have access to class data and never require access to an instance howeverto better associate such code with classand to allow such processing to be customized with inheritance as usualit would be better to code these types of functions inside the class itself to make this workwe need methods in class that are not passedand do not expecta self instance argument python supports such goals with the notion of static methods--simple functions with no self argument that are nested in class and are designed to work on class attributes instead of instance attributes static methods never receive an automatic self argumentwhether called through class or an instance they usually keep track of information that spans all instancesrather than providing behavior for instances although less commonly usedpython also supports the notion of class methods-methods of class that are passed class object in their first argument instead of an instanceregardless of whether they are called through an instance or class such methods can access class data through their class argument--what we've called self thus far--even if called through an instance normal methodsnow known in formal circles as instance methodsstill receive subject instance when calledstatic and class methods do not static methods in and the concept of static methods is the same in both python and xbut its implementation requirements have evolved somewhat in python since this book covers both versionsi need to explain the differences in the two underlying models before we get to the code reallywe already began this story in the preceding when we explored the notion of unbound methods recall that both python and always pass an instance to method that is called through an instance howeverpython treats methods fetched directly from class differently than -- difference in python lines that has nothing to do with new-style classesboth python and produce bound method when method is fetched through an instance in python xfetching method from class produces an unbound methodwhich cannot be called without manually passing an instance in python xfetching method from class produces simple functionwhich can be called normally with no instance present static and class methods |
1,584 | whether they are called through an instance or class by contrastin python we are required to pass an instance to method only if the method expects one--methods that do not include an instance argument can be called through the class without passing an instance that is allows simple functions in classas long as they do not expect and are not passed an instance argument the net effect is thatin python xwe must always declare method as static in order to call it without an instancewhether it is called through class or an instance in python xwe need not declare such methods as static if they will be called through class onlybut we must do so in order to call them through an instance to illustratesuppose we want to use class attributes to count how many instances are generated from class the following filespam pymakes first attempt--its class has counter stored as class attributea constructor that bumps up the counter by one each time new instance is createdand method that displays the counter' value rememberclass attributes are shared by all instances thereforestoring the counter in the class object itself ensures that it effectively spans all instancesclass spamnuminstances def __init__(self)spam numinstances spam numinstances def printnuminstances()print("number of instances created%sspam numinstancesthe printnuminstances method is designed to process class datanot instance data-it' about all the instancesnot any one in particular because of thatwe want to be able to call it without having to pass an instance indeedwe don' want to make an instance to fetch the number of instancesbecause this would change the number of instances we're trying to fetchin other wordswe want self-less "staticmethod whether this code' printnuminstances works or notthoughdepends on which python you useand which way you call the method--through the class or through an instance in xcalls to self-less method function through both the class and instances fail (as usuali've omitted some error text here for space) :\codec:\python \python from spam import spam spam( spam( spam(cannot call unbound class methods in methods expect self object by default spam printnuminstances(typeerrorunbound method printnuminstances(must be called with spam instance as first argument (got nothing insteada printnuminstances(typeerrorprintnuminstances(takes no arguments ( giventhe problem here is that unbound instance methods aren' exactly the same as simple functions in even though there are no arguments in the def headerthe method advanced class topics |
1,585 | workbut calls from instances failc:\codec:\python \python from spam import spam spam( spam( spam(can call functions in class in calls through instances still pass self spam printnuminstances(differs in number of instances created printnuminstances(typeerrorprintnuminstances(takes positional arguments but was given that iscalls to instance-less methods like printnuminstances made through the class fail in python but work in python on the other handcalls made through an instance fail in both pythonsbecause an instance is automatically passed to method that does not have an argument to receive itspam printnuminstances(instance printnuminstances(fails in xworks in fails in both and (unless staticif you're able to use and stick with calling self-less methods through classes onlyyou already have static method feature howeverto allow self-less methods to be called through classes in and through instances in both and xyou need to either adopt other designs or be able to somehow mark such methods as special let' look at both options in turn static method alternatives short of marking self-less method as specialyou can sometimes achieve similar results with different coding structures for exampleif you just want to call functions that access class members without an instanceperhaps the simplest idea is to use normal functions outside the classnot class methods this wayan instance isn' expected in the call the following mutation of spam py illustratesand works the same in python and xdef printnuminstances()print("number of instances created%sspam numinstancesclass spamnuminstances def __init__(self)spam numinstances spam numinstances :\codec:\python \python import spam spam spam( spam spam( spam spam(spam printnuminstances(but function may be too far removed static and class methods |
1,586 | spam spam numinstances and cannot be changed via inheritance because the class name is accessible to the simple function as global variablethis works fine alsonote that the name of the function becomes globalbut only to this single moduleit will not clash with names in other files of the program prior to static methods in pythonthis structure was the general prescription because python already provides modules as namespace-partitioning toolone could argue that there' not typically any need to package functions in classes unless they implement object behavior simple functions within modules like the one here do much of what instance-less class methods couldand are already associated with the class because they live in the same module unfortunatelythis approach is still less than ideal for one thingit adds to this file' scope an extra name that is used only for processing single class for anotherthe function is much less directly associated with the class by structurein factits definition could be hundreds of lines away perhaps worsesimple functions like this cannot be customized by inheritancesince they live outside class' namespacesubclasses cannot directly replace or extend such function by redefining it we might try to make this example work in version-neutral way by using normal method and always calling it through (or withan instanceas usualclass spamnuminstances def __init__(self)spam numinstances spam numinstances def printnuminstances(self)print("number of instances created%sspam numinstancesc:\codec:\python \python from spam import spam abc spam()spam()spam( printnuminstances(number of instances created spam printnuminstances(anumber of instances created spam(printnuminstances(number of instances created but fetching counter changes counterunfortunatelyas mentioned earliersuch an approach is completely unworkable if we don' have an instance availableand making an instance changes the class dataas illustrated in the last line here better solution would be to somehow mark method inside class as never requiring an instance the next section shows how using static and class methods todaythere is another option for coding simple functions associated with class that may be called through either the class or its instances as of python we can code advanced class topics |
1,587 | to be passed in when invoked to designate such methodsclasses call the built-in functions staticmethod and classmethodas hinted in the earlier discussion of new-style classes both mark function object as special--that isas requiring no instance if static and requiring class argument if class method for examplein the file bothmethods py (which unifies and printing with liststhough displays still vary slightly for classic classes)file bothmethods py class methodsdef imeth(selfx)print([selfx]normal instance methodpassed self def smeth( )print([ ]staticno instance passed def cmeth(clsx)print([clsx]classgets classnot instance smeth staticmethod(smethcmeth classmethod(cmethmake smeth static method (or @aheadmake cmeth class method (or @aheadnotice how the last two assignments in this code simply reassign ( rebindthe method names smeth and cmeth attributes are created and changed by any assignment in class statementso these final assignments simply overwrite the assignments made earlier by the defs as we'll see in few momentsthe special syntax works here as an alternative to this just as it does for properties--but makes little sense unless you first understand the assignment form here that it automates technicallypython now supports three kinds of class-related methodswith differing argument protocolsinstance methodspassed self instance object (the defaultstatic methodspassed no extra object (via staticmethodclass methodspassed class object (via classmethodand inherent in metaclassesmoreoverpython extends this model by also allowing simple functions in class to serve the role of static methods without extra protocolwhen called through class object only despite its namethe bothmethods py module illustrates all three method typesso let' expand on these in turn instance methods are the normal and default case that we've seen in this book an instance method must always be called with an instance object when you call it through an instancepython passes the instance to the first (leftmostargument automaticallywhen you call it through classyou must pass along the instance manuallyfrom bothmethods import methods normal instance methods obj methods(callable through instance or class obj imeth( [ static and class methods |
1,588 | [ static methodsby contrastare called without an instance argument unlike simple functions outside classtheir names are local to the scopes of the classes in which they are definedand they may be looked up by inheritance instance-less functions can be called through class normally in python xbut never by default in using the staticmethod built-in allows such methods to also be called through an instance in and through both class and an instance in python (that isthe first of the following works in without staticmethodbut the second does not)methods smeth( [ obj smeth( [ static methodcall through class no instance passed or expected static methodcall through instance instance not passed class methods are similarbut python automatically passes the class (not an instancein to class method' first (leftmostargumentwhether it is called through class or an instancemethods cmeth( [ obj cmeth( [ class methodcall through class becomes cmeth(methods class methodcall through instance becomes cmeth(methods in we'll also find that metaclass methods-- uniqueadvancedand technically distinct method type--behave similarly to the explicitly-declared class methods we're exploring here counting instances with static methods nowgiven these built-inshere is the static method equivalent of this section' instance-counting example--it marks the method as specialso it will never be passed an instance automaticallyclass spamnuminstances use static method for class data def __init__(self)spam numinstances + def printnuminstances()print("number of instances%sspam numinstancesprintnuminstances staticmethod(printnuminstancesusing the static method built-inour code now allows the self-less method to be called through the class or any instance of itin both python and xfrom spam_static import spam spam( spam( spam(spam printnuminstances(number of instances advanced class topics call as simple function |
1,589 | number of instances instance argument not passed compared to simply moving printnuminstances outside the classas prescribed earlierthis version requires an extra staticmethod call (or an line we'll see aheadhoweverit also localizes the function name in the class scope (so it won' clash with other names in the module)moves the function code closer to where it is used (inside the class statement)and allows subclasses to customize the static method with inheritance-- more convenient and powerful approach than importing functions from the files in which superclasses are coded the following subclass and new testing session illustrate (be sure to start new session after changing filesso that your from imports load the latest version of the file)class sub(spam)def printnuminstances()override static method print("extra stuff "but call back to original spam printnuminstances(printnuminstances staticmethod(printnuminstancesfrom spam_static import spamsub sub( sub( printnuminstances(extra stuff number of instances sub printnuminstances(extra stuff number of instances spam printnuminstances(number of instances call from subclass instance call from subclass itself call original version moreoverclasses can inherit the static method without redefining it--it is run without an instanceregardless of where it is defined in class treeclass other(spam)pass inherit static method verbatim other( printnuminstances(number of instances notice how this also bumps up the superclass' instance counterbecause its constructor is inherited and run-- behavior that begins to encroach on the next section' subject counting instances with class methods interestinglya class method can do similar work here--the following has the same behavior as the static method version listed earlierbut it uses class method that receives the instance' class in its first argument rather than hardcoding the class namethe class method uses the automatically passed class object genericallystatic and class methods |
1,590 | numinstances use class method instead of static def __init__(self)spam numinstances + def printnuminstances(cls)print("number of instances%scls numinstancesprintnuminstances classmethod(printnuminstancesthis class is used in the same way as the prior versionsbut its printnuminstances method receives the spam classnot the instancewhen called from both the class and an instancefrom spam_class import spam ab spam()spam( printnuminstances(number of instances spam printnuminstances(number of instances passes class to first argument also passes class to first argument when using class methodsthoughkeep in mind that they receive the most specific ( lowestclass of the call' subject this has some subtle implications when trying to update class data through the passed-in class for exampleif in module spam_class py we subclass to customize as beforeaugment spam printnuminstances to also display its cls argumentand start new testing sessionclass spamnuminstances trace class passed in def __init__(self)spam numinstances + def printnuminstances(cls)print("number of instances% % (cls numinstancescls)printnuminstances classmethod(printnuminstancesclass sub(spam)def printnuminstances(cls)override class method print("extra stuff "clsbut call back to original spam printnuminstances(printnuminstances classmethod(printnuminstancesclass other(spam)pass inherit class method verbatim the lowest class is passed in whenever class method is runeven for subclasses that have no class methods of their ownfrom spam_class import spamsubother sub( spam( printnuminstances(extra stuff number of instances sub printnuminstances(extra stuff number of instances printnuminstances(number of instances advanced class topics call from subclass instance call from subclass itself call from superclass instance |
1,591 | and python passes the lowest classsubto the class method all is well in this case-since sub' redefinition of the method calls the spam superclass' version explicitlythe superclass method in spam receives its own class in its first argument but watch what happens for an object that inherits the class method verbatimz other( printnuminstances(number of instances call from lower sub' instance this last call here passes other to spam' class method this works in this example because fetching the counter finds it in spam by inheritance if this method tried to assign to the passed class' datathoughit would update othernot spamin this specific casespam is probably better off hardcoding its own class name to update its data if it means to count instances of all its subclasses toorather than relying on the passed-in class argument counting instances per class with class methods in factbecause class methods always receive the lowest class in an instance' treestatic methods and explicit class names may be better solution for processing data local to class class methods may be better suited to processing data that may differ for each class in hierarchy code that needs to manage per-class instance countersfor examplemight be best off leveraging class methods in the followingthe top-level superclass uses class method to manage state information that varies for and is stored on each class in the tree-similar in spirit to the way instance methods manage state information that varies per class instanceclass spamnuminstances def count(cls)cls numinstances + def __init__(self)self count(count classmethod(countclass sub(spam)numinstances def __init__(self)spam __init__(selfclass other(spam)numinstances per-class instance counters cls is lowest class above instance passes self __class__ to count redefines __init__ inherits __init__ from spam_class import spamsubother spam( sub()sub(static and class methods |
1,592 | numinstancesy numinstancesz numinstances ( spam numinstancessub numinstancesother numinstances ( per-class datastatic and class methods have additional advanced roleswhich we will finesse heresee other resources for more use cases in recent python versionsthoughthe static and class method designations have become even simpler with the advent of function decoration syntax-- way to apply one function to another that has roles well beyond the static method use case that was its initial motivation this syntax also allows us to augment classes in python and --to initialize data like the numinstances counter in the last examplefor instance the next section explains how for postscript on python' method typesbe sure to watch for coverage of metaclass methods in --because these are designed to process class that is an instance of metaclassthey turn out to be very similar to the class methods defined herebut require no classmethod declarationand apply only to the shadowy metaclass realm decorators and metaclassespart because the staticmethod and classmethod call technique described in the prior section initially seemed obscure to some observersa device was eventually added to make the operation simpler python decorators--similar to the notion and syntax of annotations in java--both addressed this specific need and provided general tool for adding logic that manages both functions and classesor later calls to them this is called "decoration,but in more concrete terms is really just way to run extra processing steps at function and class definition time with explicit syntax it comes in two flavorsfunction decorators--the initial entry in this setadded in python --augment function definitions they specify special operation modes for both simple functions and classesmethods by wrapping them in an extra layer of logic implemented as another functionusually called metafunction class decorators-- later extensionadded in python and --augment class definitions they do the same for classesadding support for management of whole objects and their interfaces though perhaps simplerthey often overlap in roles with metaclasses function decorators turn out to be very general toolsthey are useful for adding many types of logic to functions besides the static and class method use cases for instancethey may be used to augment functions with code that logs calls made to themchecks the types of passed arguments during debuggingand so on function decorators can be used to manage either functions themselves or later calls to them in the latter mode advanced class topics |
1,593 | object interface python provides few built-in function decorators for operations such as marking static and class methods and defining properties (as sketched earlierthe property built-in works as decorator automatically)but programmers can also code arbitrary decorators of their own although they are not strictly tied to classesuser-defined function decorators often are coded as classes to save the original functions for later dispatchalong with other data as state information this proved such useful hook that it was extended in python and --class decorators bring augmentation to classes tooand are more directly tied to the class model like their function cohortsclass decorators may manage classes themselves or later instance creation callsand often employ delegation in the latter mode as we'll findtheir roles also often overlap with metaclasseswhen they dothe newer class decorators may offer more lightweight way to achieve the same goals function decorator basics syntacticallya function decorator is sort of runtime declaration about the function that follows function decorator is coded on line by itself just before the def statement that defines function or method it consists of the symbolfollowed by what we call metafunction-- function (or other callable objectthat manages another function static methods since python for examplemay be coded with decorator syntax like thisclass @staticmethod def meth()function decoration syntax internallythis syntax has the same effect as the following--passing the function through the decorator and assigning the result back to the original nameclass cdef meth()meth staticmethod(methname rebinding equivalent decoration rebinds the method name to the decorator' result the net effect is that calling the method function' name later actually triggers the result of its staticme thod decorator first because decorator can return any sort of objectthis allows the decorator to insert layer of logic to be run on every call the decorator function is free to return either the original function itselfor new proxy object that saves the original function passed to the decorator to be invoked indirectly after the extra logic layer runs with this additionhere' better way to code our static method example from the prior section in either python or xdecorators and metaclassespart |
1,594 | numinstances def __init__(self)spam numinstances spam numinstances @staticmethod def printnuminstances()print("number of instances created%sspam numinstancesfrom spam_static_deco import spam spam( spam( spam(spam printnuminstances(number of instances created printnuminstances(number of instances created calls from classes and instances work because they also accept and return functionsthe classmethod and property built-in functions may be used as decorators in the same way--as in the following mutation of the prior bothmethods pyfile bothmethods_decorators py class methods(object)def imeth(selfx)print([selfx]object needed in for property setters normal instance methodpassed self @staticmethod def smeth( )print([ ]staticno instance passed @classmethod def cmeth(clsx)print([clsx]classgets classnot instance @property propertycomputed on fetch def name(self)return 'bob self __class__ __name__ from bothmethods_decorators import methods obj methods(obj imeth( [ obj smeth( [ obj cmeth( [ obj name 'bob methodskeep in mind that staticmethod and its kin here are still built-in functionsthey may be used in decoration syntaxjust because they take function as an argument and return callable to which the original function name can be rebound in factany such advanced class topics |
1,595 | the next section explains first look at user-defined function decorators although python provides handful of built-in functions that can be used as decoratorswe can also write custom decorators of our own because of their wide utilitywe're going to devote an entire to coding decorators in the final part of this book as quick examplethoughlet' look at simple user-defined decorator at work recall from that the __call__ operator overloading method implements function-call interface for class instances the following code uses this to define call proxy class that saves the decorated function in the instance and catches calls to the original name because this is classit also has state information-- counter of calls madeclass tracerdef __init__(selffunc)remember originalinit counter self calls self func func def __call__(self*args)on later callsadd logicrun original self calls + print('call % to % (self callsself func __name__)return self func(*args@tracer def spam(abc)return same as spam tracer(spamwrap spam in decorator object print(spam( )print(spam(' '' '' ')really calls the tracer wrapper object invokes __call__ in class because the spam function is run through the tracer decoratorwhen the original spam name is called it actually triggers the __call__ method in the class this method counts and logs the calland then dispatches it to the original wrapped function note how the *name argument syntax is used to pack and unpack the passed-in argumentsbecause of thisthis decorator can be used to wrap any function with any number of positional arguments the net effectagainis to add layer of logic to the original spam function here is the script' and output--the first line comes from the tracer classand the second gives the return value of the spam function itselfc:\codepython tracer py call to spam call to spam abc trace through this example' code for more insight as it isthis decorator works for any function that takes positional argumentsbut it does not handle keyword argudecorators and metaclassespart |
1,596 | __call__ would be passed tracer instance onlyas we'll see in part viiithere are variety of ways to code function decoratorsincluding nested def statementssome of the alternatives are better suited to methods than the version shown here for exampleby using nested functions with enclosing scopes for stateinstead of callable class instances with attributesfunction decorators often become more broadly applicable to class-level methods too we'll postpone the full details on thisbut here' brief look at this closure based coding modelit uses function attributes for counter state for portabilitybut could leverage variables and nonlocal instead in onlydef tracer(func)remember original def oncall(*args)on later calls oncall calls + print('call % to % (oncall callsfunc __name__)return func(*argsoncall calls return oncall class @tracer def spam(self,abc)return (print( spam( )print( spam(' '' '' ')same output as tracer (in tracer pya first look at class decorators and metaclasses function decorators turned out to be so useful that python and expanded the modelallowing decorators to be applied to classes as well as functions in shortclass decorators are similar to function decoratorsbut they are run at the end of class statement to rebind class name to callable as suchthey can be used to either manage classes just after they are createdor insert layer of wrapper logic to manage instances when they are later created symbolicallythe code structuredef decorator(aclass)@decorator class cclass decoration syntax is mapped to the following equivalentdef decorator(aclass)class cc decorator(cname rebinding equivalent the class decorator is free to augment the class itselfor return proxy object that intercepts later instance construction calls for examplein the code of the section "counting instances per class with class methodson page we could use this advanced class topics |
1,597 | hook to automatically augment the classes with instance counters and any other data requireddef count(aclass)aclass numinstances return aclass return class itselfinstead of wrapper @count class spamsame as spam count(spam@count class sub(spam)numinstances not needed here @count class other(spam)in factas codedthis decorator can be applied to class or functions--it happily returns the object being defined in either context after initializing the object' attribute@count def spam()pass like spam count(spam@count class otherpass like other count(otherspam numinstances other numinstances both are set to zero though this decorator manages function or class itselfas we'll see later in this bookclass decorators can also manage an object' entire interface by intercepting construction callsand wrapping the new instance object in proxy that deploys attribute accessor tools to intercept later requests-- multilevel coding technique we'll use to implement class attribute privacy in here' preview of the modeldef decorator(cls)on decoration class proxydef __init__(self*args)on instance creationmake cls self wrapped cls(*argsdef __getattr__(selfname)on attribute fetchextra ops here return getattr(self wrappednamereturn proxy @decorator class cx (like decorator(cmakes proxy that wraps cand catches later attr metaclassesmentioned briefly earlierare similarly advanced class-based tool whose roles often intersect with those of class decorators they provide an alternate modelwhich routes the creation of class object to subclass of the top-level type classat the conclusion of class statementclass meta(type)def __new__(metaclassnamesupersclassdict)extra logic class creation via type call decorators and metaclassespart |
1,598 | my creation routed to meta like meta(' '()}in python xthe effect is the samebut the coding differs--use class attribute instead of keyword argument in the class headerclass c__metaclass__ meta my creation routed to meta in either linepython calls class' metaclass to create the new class objectpassing in the data defined during the class statement' runin xthe metaclass simply defaults to the classic class creatorclassname meta(classnamesuperclassesattributedictto assume control of the creation or initialization of new class objecta metaclass generally redefines the __new__ or __init__ method of the type class that normally intercepts this call the net effectas with class decoratorsis to define code to be run automatically at class creation time herethis step binds the class name to the result of call to user-defined metaclass in facta metaclass need not be class at all-- possibility we'll explore later that blurs some of the distinction between this tool and decoratorsand may even qualify the two as functionally equivalent in many roles both schemesclass decorators and metaclassesare free to augment class or return an arbitrary object to replace it-- protocol with almost limitless class-based customization possibilities as we'll see latermetaclasses may also define methods that process their instance classesrather than normal instances of them-- technique that' similar to class methodsand might be emulated in spirit by methods and data in class decorator proxiesor even class decorator that returns metaclass instance such mindbinding concepts will require ' conceptual groundwork (and quite possibly sedation!for more details naturallythere' much more to the decorator and metaclass stories than 've shown here although they are general mechanism whose usage may be required by some packagescoding new user-defined decorators and metaclasses is an advanced topic of interest primarily to tool writersnot application programmers because of thiswe'll defer additional coverage until the final and optional part of this book shows how to code properties using function decorator syntax in more depth has much more on decoratorsincluding more comprehensive examples covers metaclassesand more on the class and instance management story advanced class topics |
1,599 | to see python at work in more substantial examples than much of the rest of the book was able to provide for nowlet' move on to our final class-related topic the super built-in functionfor better or worseso fari've mentioned python' super built-in function only briefly in passing because it is relatively uncommon and may even be controversial to use given this call' increased visibility in recent yearsthoughit merits some further elaboration in this edition besides introducing superthis section also serves as language design case study to close out on so many tools whose presence may to some seem curious in scripting language like python some of this section calls this proliferation of tools into questionand encourage you to judge any subjective content here for yourself (and we'll return to such things at the end of this book after we've expanded on other advanced tools such as metaclasses and descriptorsstillpython' rapid growth rate in recent years represents strategic decision point for its community going forwardand super seems as good representative example as any the great super debate as noted in and python has super built-in function that can be used to invoke superclass methods genericallybut was deferred until this point of the book this was deliberate--because super has substantial downsides in typical codeand sole use case that seems obscure and complex to many observersmost beginners are better served by the traditional explicit-name call scheme used so far see the sidebar "what about super?on page in for brief summary of the rationale for this policy the python community itself seems split on this subjectwith online articles about it running the gamut from "python' super considered harmfulto "python' super(considered super!" franklyin my live classes this call seems to be most often of interest to java programmers starting to use python anewbecause of its conceptual similarity to tool in that language (many new python feature ultimately owes its existence to programmers of other languages bringing their old habits to new modelpython' super is not java' --it translates differently to python' multiple inheritanceand has both are opinion pieces in partbut are suggested reading the first was eventually retitled "python' super is niftybut you can' use it,and is today at its subjective tone--the second article ("python' super(considered super!"alone somehow found its way into python' official library manualsee its link in the manual' super section and consider demanding that differing opinions be represented more evenly in your toolsdocumentationor omitted altogether python' manuals are not the place for personal opinion and one-sided propagandathe super built-in functionfor better or worse |
Subsets and Splits