id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
3,300 | let' look at second contrived example that illustrates this problem more clearly here we have base class that has method named call_me two subclasses override that methodand then another subclass extends both of these using multiple inheritance this is called diamond inheritance because of the diamond shape of the class diagrambaseclass +call_me(leftsubclass rightsubclass +call_me(+call_me(subclass +call_me(let' convert this diagram to codethis example shows when the methods are calledclass baseclassnum_base_calls def call_me(self)print("calling method on base class"self num_base_calls + class leftsubclass(baseclass)num_left_calls def call_me(self)baseclass call_me(selfprint("calling method on left subclass"self num_left_calls + class rightsubclass(baseclass)num_right_calls def call_me(self)baseclass call_me(selfprint("calling method on right subclass"self num_right_calls + class subclass(leftsubclassrightsubclass) |
3,301 | num_sub_calls def call_me(self)leftsubclass call_me(selfrightsubclass call_me(selfprint("calling method on subclass"self num_sub_calls + this example simply ensures that each overridden call_me method directly calls the parent method with the same name it lets us know each time method is called by printing the information to the screen it also updates static variable on the class to show how many times it has been called if we instantiate one subclass object and call the method on it oncewe get this outputs subclass( call_me(calling method on base class calling method on left subclass calling method on base class calling method on right subclass calling method on subclass prints num_sub_callss num_left_callss num_right_callss num_base_calls thus we can clearly see the base class' call_me method being called twice this could lead to some insidious bugs if that method is doing actual work--like depositing into bank account--twice the thing to keep in mind with multiple inheritance is that we only want to call the "nextmethod in the class hierarchynot the "parentmethod in factthat next method may not be on parent or ancestor of the current class the super keyword comes to our rescue once again indeedsuper was originally developed to make complicated forms of multiple inheritance possible here is the same code written using superclass baseclassnum_base_calls def call_me(self) |
3,302 | print("calling method on base class"self num_base_calls + class leftsubclass(baseclass)num_left_calls def call_me(self)super(call_me(print("calling method on left subclass"self num_left_calls + class rightsubclass(baseclass)num_right_calls def call_me(self)super(call_me(print("calling method on right subclass"self num_right_calls + class subclass(leftsubclassrightsubclass)num_sub_calls def call_me(self)super(call_me(print("calling method on subclass"self num_sub_calls + the change is pretty minorwe simply replaced the naive direct calls with calls to super()although the bottom subclass only calls super once rather than having to make the calls for both the left and right the change is simple enoughbut look at the difference when we execute its subclass( call_me(calling method on base class calling method on right subclass calling method on left subclass calling method on subclass print( num_sub_callss num_left_callss num_right_callss num_base_calls looks goodour base method is only being called once but what is super(actually doing heresince the print statements are executed after the super callsthe printed output is in the order each method is actually executed let' look at the output from back to front to see who is calling what |
3,303 | firstcall_me of subclass calls super(call_me()which happens to refer to leftsubclass call_me(the leftsubclass call_me(method then calls super(call_me()but in this casesuper(is referring to rightsubclass call_ me(pay particular attention to thisthe super call is not calling the method on the superclass of leftsubclass (which is baseclassratherit is calling rightsubclasseven though it is not direct parent of leftsubclassthis is the next methodnot the parent method rightsubclass then calls baseclass and the super calls have ensured each method in the class hierarchy is executed once different sets of arguments this is going to make things complicated as we return to our friend multiple inheritance example in the __init__ method for friendwe were originally calling __init__ for both parent classeswith different sets of argumentscontact __init__(selfnameemailaddressholder __init__(selfstreetcitystatecodehow can we manage different sets of arguments when using superwe don' necessarily know which class super is going to try to initialize first even if we didwe need way to pass the "extraarguments so that subsequent calls to superon other subclassesreceive the right arguments specificallyif the first call to super passes the name and email arguments to contact __init__and contact __init__ then calls superit needs to be able to pass the address-related arguments to the "nextmethodwhich is addressholder __init__ this is problem whenever we want to call superclass methods with the same namebut with different sets of arguments most oftenthe only time you would want to call superclass with completely different set of arguments is in __init__as we're doing here even with regular methodsthoughwe may want to add optional parameters that only make sense to one subclass or set of subclasses sadlythe only way to solve this problem is to plan for it from the beginning we have to design our base class parameter lists to accept keyword arguments for any parameters that are not required by every subclass implementation finallywe must ensure the method freely accepts unexpected arguments and passes them on to its super callin case they are necessary to later methods in the inheritance order |
3,304 | python' function parameter syntax provides all the tools we need to do thisbut it makes the overall code look cumbersome have look at the proper version of the friend multiple inheritance codeclass contactall_contacts [def __init__(selfname=''email=''**kwargs)super(__init__(**kwargsself name name self email email self all_contacts append(selfclass addressholderdef __init__(selfstreet=''city=''state=''code=''**kwargs)super(__init__(**kwargsself street street self city city self state state self code code class friend(contactaddressholder)def __init__(selfphone=''**kwargs)super(__init__(**kwargsself phone phone we've changed all arguments to keyword arguments by giving them an empty string as default value we've also ensured that **kwargs parameter is included to capture any additional parameters that our particular method doesn' know what to do with it passes these parameters up to the next class with the super call if you aren' familiar with the **kwargs syntaxit basically collects any keyword arguments passed into the method that were not explicitly listed in the parameter list these arguments are stored in dictionary named kwargs (we can call the variable whatever we likebut convention suggests kwor kwargswhen we call different method (for examplesuper(__init__with **kwargs syntaxit unpacks the dictionary and passes the results to the method as normal keyword arguments we'll cover this in detail in python object-oriented shortcuts |
3,305 | the previous example does what it is supposed to do but it' starting to look messyand it has become difficult to answer the questionwhat arguments do we need to pass into friend __init__this is the foremost question for anyone planning to use the classso docstring should be added to the method to explain what is happening furthereven this implementation is insufficient if we want to reuse variables in parent classes when we pass the **kwargs variable to superthe dictionary does not include any of the variables that were included as explicit keyword arguments for examplein friend __init__the call to super does not have phone in the kwargs dictionary if any of the other classes need the phone parameterwe need to ensure it is in the dictionary that is passed worseif we forget to do thisit will be tough to debug because the superclass will not complainbut will simply assign the default value (in this casean empty stringto the variable there are few ways to ensure that the variable is passed upwards assume the contact class doesfor some reasonneed to be initialized with phone parameterand the friend class will also need access to it we can do any of the followingdon' include phone as an explicit keyword argument insteadleave it in the kwargs dictionary friend can look it up using the syntax kwargs['phone'when it passes **kwargs to the super callphone will still be in the dictionary make phone an explicit keyword argument but update the kwargs dictionary before passing it to superusing the standard dictionary syntax kwargs['phone'phone make phone an explicit keyword argumentbut update the kwargs dictionary using the kwargs update method this is useful if you have several arguments to update you can create the dictionary passed into update using either the dict(phone=phoneconstructoror the dictionary syntax {'phone'phonemake phone an explicit keyword argumentbut pass it to the super call explicitly with the syntax super(__init__(phone=phone**kwargswe have covered many of the caveats involved with multiple inheritance in python when we need to account for all the possible situationswe have to plan for them and our code will get messy basic multiple inheritance can be handy butin many caseswe may want to choose more transparent way of combining two disparate classesusually using composition or one of the design patterns we'll be covering in python design patterns and python design patterns ii |
3,306 | polymorphism we were introduced to polymorphism in object-oriented design it is fancy name describing simple conceptdifferent behaviors happen depending on which subclass is being usedwithout having to explicitly know what the subclass actually is as an exampleimagine program that plays audio files media player might need to load an audiofile object and then play it we' put play(method on the objectwhich is responsible for decompressing or extracting the audio and routing it to the sound card and speakers the act of playing an audiofile could feasibly be as simple asaudio_file play(howeverthe process of decompressing and extracting an audio file is very different for different types of files the wav files are stored uncompressedwhile mp wmaand ogg files all have totally different compression algorithms we can use inheritance with polymorphism to simplify the design each type of file can be represented by different subclass of audiofilefor examplewavfilemp file each of these would have play(methodbut that method would be implemented differently for each file to ensure the correct extraction procedure is followed the media player object would never need to know which subclass of audiofile it is referring toit just calls play(and polymorphically lets the object take care of the actual details of playing let' look at quick skeleton showing how this might lookclass audiofiledef __init__(selffilename)if not filename endswith(self ext)raise exception("invalid file format"self filename filename class mp file(audiofile)ext "mp def play(self)print("playing {as mp format(self filename)class wavfile(audiofile)ext "wavdef play(self) |
3,307 | print("playing {as wavformat(self filename)class oggfile(audiofile)ext "oggdef play(self)print("playing {as oggformat(self filename)all audio files check to ensure that valid extension was given upon initialization but did you notice how the __init__ method in the parent class is able to access the ext class variable from different subclassesthat' polymorphism at work if the filename doesn' end with the correct nameit raises an exception (exceptions will be covered in detail in the next the fact that audiofile doesn' actually store reference to the ext variable doesn' stop it from being able to access it on the subclass in additioneach subclass of audiofile implements play(in different way (this example doesn' actually play the musicaudio compression algorithms really deserve separate book!this is also polymorphism in action the media player can use the exact same code to play fileno matter what type it isit doesn' care what subclass of audiofile it is looking at the details of decompressing the audio file are encapsulated if we test this exampleit works as we would hopeogg oggfile("myfile ogg"ogg play(playing myfile ogg as ogg mp mp file("myfile mp "mp play(playing myfile mp as mp not_an_mp mp file("myfile ogg"traceback (most recent call last)file ""line in file "polymorphic_audio py"line in __init__ raise exception("invalid file format"exceptioninvalid file format see how audiofile __init__ is able to check the file type without actually knowing what subclass it is referring to |
3,308 | polymorphism is actually one of the coolest things about object-oriented programmingand it makes some programming designs obvious that weren' possible in earlier paradigms howeverpython makes polymorphism less cool because of duck typing duck typing in python allows us to use any object that provides the required behavior without forcing it to be subclass the dynamic nature of python makes this trivial the following example does not extend audiofilebut it can be interacted with in python using the exact same interfaceclass flacfiledef __init__(selffilename)if not filename endswith(flac")raise exception("invalid file format"self filename filename def play(self)print("playing {as flacformat(self filename)our media player can play this object just as easily as one that extends audiofile polymorphism is one of the most important reasons to use inheritance in many object-oriented contexts because any objects that supply the correct interface can be used interchangeably in pythonit reduces the need for polymorphic common superclasses inheritance can still be useful for sharing code butif all that is being shared is the public interfaceduck typing is all that is required this reduced need for inheritance also reduces the need for multiple inheritanceoftenwhen multiple inheritance appears to be valid solutionwe can just use duck typing to mimic one of the multiple superclasses of coursejust because an object satisfies particular interface (by providing required methods or attributesdoes not mean it will simply work in all situations it has to fulfill that interface in way that makes sense in the overall system just because an object provides play(method does not mean it will automatically work with media player for exampleour chess ai object from object-oriented designmay have play(method that moves chess piece even though it satisfies the interfacethis class would likely break in spectacular ways if we tried to plug it into media playeranother useful feature of duck typing is that the duck-typed object only needs to provide those methods and attributes that are actually being accessed for exampleif we needed to create fake file object to read data fromwe can create new object that has read(methodwe don' have to override the write method if the code that is going to interact with the object will only be reading from the file more succinctlyduck typing doesn' need to provide the entire interface of an object that is availableit only needs to fulfill the interface that is actually accessed |
3,309 | abstract base classes while duck typing is usefulit is not always easy to tell in advance if class is going to fulfill the protocol you require thereforepython introduced the idea of abstract base classes abstract base classesor abcsdefine set of methods and properties that class must implement in order to be considered duck-type instance of that class the class can extend the abstract base class itself in order to be used as an instance of that classbut it must supply all the appropriate methods in practiceit' rarely necessary to create new abstract base classesbut we may find occasions to implement instances of existing abcs we'll cover implementing abcs firstand then briefly see how to create your own if you should ever need to using an abstract base class most of the abstract base classes that exist in the python standard library live in the collections module one of the simplest ones is the container class let' inspect it in the python interpreter to see what methods this class requiresfrom collections import container container __abstractmethods__ frozenset(['__contains__']sothe container class has exactly one abstract method that needs to be implemented__contains__ you can issue help(container __contains__to see what the function signature should look likehelp on method __contains__ in module _abcoll__contains__(selfxunbound _abcoll container method sowe see that __contains__ needs to take single argument unfortunatelythe help file doesn' tell us much about what that argument should bebut it' pretty obvious from the name of the abc and the single method it implements that this argument is the value the user is checking to see if the container holds this method is implemented by liststrand dict to indicate whether or not given value is in that data structure howeverwe can also define silly container that tells us whether given value is in the set of odd integersclass oddcontainerdef __contains__(selfx)if not isinstance(xintor not return false return true |
3,310 | nowwe can instantiate an oddcontainer object and determine thateven though we did not extend containerthe class is container objectfrom collections import container odd_container oddcontainer(isinstance(odd_containercontainertrue issubclass(oddcontainercontainertrue and that is why duck typing is way more awesome than classical polymorphism we can create is relationships without the overhead of using inheritance (or worsemultiple inheritancethe interesting thing about the container abc is that any class that implements it gets to use the in keyword for free in factin is just syntax sugar that delegates to the __contains__ method any class that has __contains__ method is container and can therefore be queried by the in keywordfor example in odd_container true in odd_container false in odd_container true " stringin odd_container false creating an abstract base class as we saw earlierit' not necessary to have an abstract base class to enable duck typing howeverimagine we were creating media player with third-party plugins it is advisable to create an abstract base class in this case to document what api the thirdparty plugins should provide the abc module provides the tools you need to do thisbut 'll warn you in advancethis requires some of python' most arcane conceptsimport abc class medialoader(metaclass=abc abcmeta)@abc abstractmethod def play(self)pass @abc abstractproperty def ext(self) |
3,311 | pass @classmethod def __subclasshook__(clsc)if cls is medialoaderattrs set(dir( )if set(cls __abstractmethods__<attrsreturn true return notimplemented this is complicated example that includes several python features that won' be explained until later in this book it is included here for completenessbut you don' need to understand all of it to get the gist of how to create your own abc the first weird thing is the metaclass keyword argument that is passed into the class where you would normally see the list of parent classes this is rarely used construct from the mystic art of metaclass programming we won' be covering metaclasses in this bookso all you need to know is that by assigning the abcmeta metaclassyou are giving your class superpower (or at least superclassabilities nextwe see the @abc abstractmethod and @abc abstractproperty constructs these are python decorators we'll discuss those in when to use object-oriented programming for nowjust know that by marking method or property as being abstractyou are stating that any subclass of this class must implement that method or supply that property in order to be considered proper member of the class see what happens if you implement subclasses that do or don' supply those propertiesclass wav(medialoader)pass wav(traceback (most recent call last)file ""line in typeerrorcan' instantiate abstract class wav with abstract methods extplay class ogg(medialoader)ext oggdef play(self)pass ogg( |
3,312 | since the wav class fails to implement the abstract attributesit is not possible to instantiate that class the class is still legal abstract classbut you' have to subclass it to actually do anything the ogg class supplies both attributesso it instantiates cleanly going back to the medialoader abclet' dissect that __subclasshook__ method it is basically saying that any class that supplies concrete implementations of all the abstract attributes of this abc should be considered subclass of medialoadereven if it doesn' actually inherit from the medialoader class more common object-oriented languages have clear separation between the interface and the implementation of class for examplesome languages provide an explicit interface keyword that allows us to define the methods that class must have without any implementation in such an environmentan abstract class is one that provides both an interface and concrete implementation of some but not all methods any class can explicitly state that it implements given interface python' abcs help to supply the functionality of interfaces without compromising on the benefits of duck typing demystifying the magic you can copy and paste the subclass code without understanding it if you want to make abstract classes that fulfill this particular contract we'll cover most of the unusual syntaxes throughout the bookbut let' go over it line by line to get an overview @classmethod this decorator marks the method as class method it essentially says that the method can be called on class instead of an instantiated objectdef __subclasshook__(clsc)this defines the __subclasshook__ class method this special method is called by the python interpreter to answer the questionis the class subclass of this classif cls is medialoaderwe check to see if the method was called specifically on this classrather thansay subclass of this class this preventsfor examplethe wav class from being thought of as parent class of the ogg classattrs set(dir( ) |
3,313 | all this line does is get the set of methods and properties that the class hasincluding any parent classes in its class hierarchyif set(cls __abstractmethods__<attrsthis line uses set notation to see whether the set of abstract methods in this class have been supplied in the candidate class note that it doesn' check to see whether the methods have been implementedjust if they are there thusit' possible for class to be subclass and yet still be an abstract class itself return true if all the abstract methods have been suppliedthen the candidate class is subclass of this class and we return true the method can legally return one of the three valuestruefalseor notimplemented true and false indicate that the class is or is not definitively subclass of this classreturn notimplemented if any of the conditionals have not been met (that isthe class is not medialoader or not all abstract methods have been supplied)then return notimplemented this tells the python machinery to use the default mechanism (does the candidate class explicitly extend this class?for subclass detection in shortwe can now define the ogg class as subclass of the medialoader class without actually extending the medialoader classclass ogg()ext oggdef play(self)print("this will play an ogg file"issubclass(oggmedialoadertrue isinstance(ogg()medialoadertrue case study let' try to tie everything we've learned together with larger example we'll be designing simple real estate application that allows an agent to manage properties available for purchase or rent there will be two types of propertiesapartments and houses the agent needs to be able to enter few relevant details about new propertieslist all currently available propertiesand mark property as sold or rented for brevitywe won' worry about editing property details or reactivating property after it is sold |
3,314 | the project will allow the agent to interact with the objects using the python interpreter prompt in this world of graphical user interfaces and web applicationsyou might be wondering why we're creating such old-fashioned looking programs simply putboth windowed programs and web applications require lot of overhead knowledge and boilerplate code to make them do what is required if we were developing software using either of these paradigmswe' get so lost in gui programming or web programming that we' lose sight of the object-oriented principles we're trying to master luckilymost gui and web frameworks utilize an object-oriented approachand the principles we're studying now will help in understanding those systems in the future we'll discuss them both briefly in concurrencybut complete details are far beyond the scope of single book looking at our requirementsit seems like there are quite few nouns that might represent classes of objects in our system clearlywe'll need to represent property houses and apartments may need separate classes rentals and purchases also seem to require separate representation since we're focusing on inheritance right nowwe'll be looking at ways to share behavior using inheritance or multiple inheritance house and apartment are both types of propertiesso property can be superclass of those two classes rental and purchase will need some extra thoughtif we use inheritancewe'll need to have separate classesfor examplefor houserental and housepurchaseand use multiple inheritance to combine them this feels little clunky compared to composition or association-based designbut let' run with it and see what we come up with now thenwhat attributes might be associated with property classregardless of whether it is an apartment or housemost people will want to know the square footagenumber of bedroomsand number of bathrooms (there are numerous other attributes that might be modeledbut we'll keep it simple for our prototype if the property is houseit will want to advertise the number of storieswhether it has garage (attacheddetachedor none)and whether the yard is fenced an apartment will want to indicate if it has balconyand if the laundry is ensuitecoinor off-site both property types will require method to display the characteristics of that property at the momentno other behaviors are apparent rental properties will need to store the rent per monthwhether the property is furnishedand whether utilities are includedand if notwhat they are estimated to be properties for purchase will need to store the purchase price and estimated annual property taxes for our applicationwe'll only need to display this dataso we can get away with just adding display(method similar to that used in the other classes |
3,315 | finallywe'll need an agent object that holds list of all propertiesdisplays those propertiesand allows us to create new ones creating properties will entail prompting the user for the relevant details for each property type this could be done in the agent objectbut then agent would need to know lot of information about the types of properties this is not taking advantage of polymorphism another alternative would be to put the prompts in the initializer or even constructor for each classbut this would not allow the classes to be applied in gui or web application in the future better idea is to create static method that does the prompting and returns dictionary of the prompted parameters thenall the agent has to do is prompt the user for the type of property and payment methodand ask the correct class to instantiate itself that' lot of designingthe following class diagram may communicate our design decisions little more clearlyagent +property_list +list_properties(show_all=false+add_property(property_type,purchase_typehouse apartment +balcony +laundry +display(+prompt_init(+num_stories +garage +fenced_yardboolean property +square_feet +num_bedrooms +num_bathrooms +display(+prompt_init(+display(+prompt_init(houserental purchase housepurchase +price +taxes apartmentpurchase +display(+prompt_init(apartmentrental rental +furnished +utilities +rent +display(+prompt_init( |
3,316 | wowthat' lot of inheritance arrowsi don' think it would be possible to add another level of inheritance without crossing arrows multiple inheritance is messy businesseven at the design stage the trickiest aspects of these classes is going to be ensuring superclass methods get called in the inheritance hierarchy let' start with the property implementationclass propertydef __init__(selfsquare_feet=''beds=''baths=''**kwargs)super(__init__(**kwargsself square_feet square_feet self num_bedrooms beds self num_baths baths def display(self)print("property details"print("================"print("square footage{}format(self square_feet)print("bedrooms{}format(self num_bedrooms)print("bathrooms{}format(self num_baths)print(def prompt_init()return dict(square_feet=input("enter the square feet")beds=input("enter number of bedrooms")baths=input("enter number of baths")prompt_init staticmethod(prompt_initthis class is pretty straightforward we've already added the extra **kwargs parameter to __init__ because we know it' going to be used in multiple inheritance situation we've also included call to super(__init__ in case we are not the last call in the multiple inheritance chain in this casewe're consuming the keyword arguments because we know they won' be needed at other levels of the inheritance hierarchy we see something new in the prompt_init method this method is made into static method immediately after it is initially created static methods are associated only with class (something like class variables)rather than specific object instance hencethey have no self argument because of thisthe super keyword won' work (there is no parent objectonly parent class)so we simply call the static method on the parent class directly this method uses the python dict constructor to create dictionary of values that can be passed into __init__ the value for each key is prompted with call to input |
3,317 | the apartment class extends propertyand is similar in structureclass apartment(property)valid_laundries ("coin""ensuite""none"valid_balconies ("yes""no""solarium"def __init__(selfbalcony=''laundry=''**kwargs)super(__init__(**kwargsself balcony balcony self laundry laundry def display(self)super(display(print("apartment details"print("laundry%sself laundryprint("has balcony%sself balconydef prompt_init()parent_init property prompt_init(laundry 'while laundry lower(not in apartment valid_laundrieslaundry input("what laundry facilities does "the property have({})format"join(apartment valid_laundries))balcony 'while balcony lower(not in apartment valid_balconiesbalcony input"does the property have balcony"({})format"join(apartment valid_balconies))parent_init update("laundry"laundry"balcony"balcony }return parent_init prompt_init staticmethod(prompt_initthe display(and __init__(methods call their respective parent class methods using super(to ensure the property class is properly initialized |
3,318 | the prompt_init static method is now getting dictionary values from the parent classand then adding some additional values of its own it calls the dict update method to merge the new dictionary values into the first one howeverthat prompt_init method is looking pretty uglyit loops twice until the user enters valid input using structurally similar code but different variables it would be nice to extract this validation logic so we can maintain it in only one locationit will likely also be useful to later classes with all the talk on inheritancewe might think this is good place to use mixin insteadwe have chance to study situation where inheritance is not the best solution the method we want to create will be used in static method if we were to inherit from class that provided validation functionalitythe functionality would also have to be provided as static method that did not access any instance variables on the class if it doesn' access any instance variableswhat' the point of making it class at allwhy don' we just make this validation functionality module-level function that accepts an input string and list of valid answersand leave it at thatlet' explore what this validation function would look likedef get_valid_input(input_stringvalid_options)input_string +({}format("join(valid_options)response input(input_stringwhile response lower(not in valid_optionsresponse input(input_stringreturn response we can test this function in the interpreterindependent of all the other classes we've been working on this is good signit means different pieces of our design are not tightly coupled to each other and can later be improved independentlywithout affecting other pieces of code get_valid_input("what laundry?"("coin""ensuite""none")what laundry(coinensuitenonehi what laundry(coinensuitenonecoin 'coinnowlet' quickly update our apartment prompt_init method to use this new function for validationdef prompt_init()parent_init property prompt_init(laundry get_valid_input |
3,319 | "what laundry facilities does "the property have"apartment valid_laundriesbalcony get_valid_input"does the property have balcony"apartment valid_balconiesparent_init update("laundry"laundry"balcony"balcony }return parent_init prompt_init staticmethod(prompt_initthat' much easier to read (and maintain!than our original version now we're ready to build the house class this class has parallel structure to apartmentbut refers to different prompts and variablesclass house(property)valid_garage ("attached""detached""none"valid_fenced ("yes""no"def __init__(selfnum_stories=''garage=''fenced=''**kwargs)super(__init__(**kwargsself garage garage self fenced fenced self num_stories num_stories def display(self)super(display(print("house details"print("of stories{}format(self num_stories)print("garage{}format(self garage)print("fenced yard{}format(self fenced)def prompt_init()parent_init property prompt_init(fenced get_valid_input("is the yard fenced"house valid_fencedgarage get_valid_input("is there garage"house valid_garage |
3,320 | num_stories input("how many stories"parent_init update("fenced"fenced"garage"garage"num_stories"num_stories }return parent_init prompt_init staticmethod(prompt_initthere' nothing new to explore hereso let' move on to the purchase and rental classes in spite of having apparently different purposesthey are also similar in design to the ones we just discussedclass purchasedef __init__(selfprice=''taxes=''**kwargs)super(__init__(**kwargsself price price self taxes taxes def display(self)super(display(print("purchase details"print("selling price{}format(self price)print("estimated taxes{}format(self taxes)def prompt_init()return dictprice=input("what is the selling price")taxes=input("what are the estimated taxes")prompt_init staticmethod(prompt_initclass rentaldef __init__(selffurnished=''utilities=''rent=''**kwargs)super(__init__(**kwargsself furnished furnished self rent rent self utilities utilities def display(self)super(display(print("rental details" |
3,321 | print("rent{}format(self rent)print("estimated utilities{}formatself utilities)print("furnished{}format(self furnished)def prompt_init()return dictrent=input("what is the monthly rent")utilities=input"what are the estimated utilities")furnished get_valid_input"is the property furnished"("yes""no"))prompt_init staticmethod(prompt_initthese two classes don' have superclass (other than object)but we still call super(__init__ because they are going to be combined with the other classesand we don' know what order the super calls will be made in the interface is similar to that used for house and apartmentwhich is very useful when we combine the functionality of these four classes in separate subclasses for exampleclass houserental(rentalhouse)def prompt_init()init house prompt_init(init update(rental prompt_init()return init prompt_init staticmethod(prompt_initthis is slightly surprisingas the class on its own has neither an __init__ nor display methodbecause both parent classes appropriately call super in these methodswe only have to extend those classes and the classes will behave in the correct order this is not the case with prompt_initof coursesince it is static method that does not call superso we implement this one explicitly we should test this class to make sure it is behaving properly before we write the other three combinationsinit houserental prompt_init(enter the square feet enter number of bedrooms enter number of baths is the yard fenced(yesnono is there garage(attacheddetachednonenone how many stories what is the monthly rent what are the estimated utilities |
3,322 | is the property furnished(yesnono house houserental(**inithouse display(property details ===============square footage bedrooms bathrooms house details of stories garagenone fenced yardno rental details rent estimated utilities furnishedno it looks like it is working fine the prompt_init method is prompting for initializers to all the super classesand display(is also cooperatively calling all three superclasses the order of the inherited classes in the preceding example is important if we had written class houserental(houserentalinstead of class houserental(rentalhouse)display(would not have called rental display()when display is called on our version of houserentalit refers to the rental version of the methodwhich calls super display(to get the house versionwhich again calls super display(to get the property version if we reversed itdisplay would refer to the house class' display(when super is calledit calls the method on the property parent class but property does not have call to super in its display method this means rental class' display method would not be calledby placing the inheritance list in the order we didwe ensure that rental calls superwhich then takes care of the house side of the hierarchy you might think we could have added super call to property display()but that will fail because the next superclass of property is objectand object does not have display method another way to fix this is to allow rental and purchase to extend the property class instead of deriving directly from object (or we could modify the method resolution order dynamicallybut that is beyond the scope of this book |
3,323 | now that we have tested itwe are prepared to create the rest of our combined subclassesclass apartmentrental(rentalapartment)def prompt_init()init apartment prompt_init(init update(rental prompt_init()return init prompt_init staticmethod(prompt_initclass apartmentpurchase(purchaseapartment)def prompt_init()init apartment prompt_init(init update(purchase prompt_init()return init prompt_init staticmethod(prompt_initclass housepurchase(purchasehouse)def prompt_init()init house prompt_init(init update(purchase prompt_init()return init prompt_init staticmethod(prompt_initthat should be the most intense designing out of our waynow all we have to do is create the agent classwhich is responsible for creating new listings and displaying existing ones let' start with the simpler storing and listing of propertiesclass agentdef __init__(self)self property_list [def display_properties(self)for property in self property_listproperty display(adding property will require first querying the type of property and whether property is for purchase or rental we can do this by displaying simple menu once this has been determinedwe can extract the correct subclass and prompt for all the details using the prompt_init hierarchy we've already developed sounds simpleit is let' start by adding dictionary class variable to the agent classtype_map ("house""rental")houserental("house""purchase")housepurchase |
3,324 | ("apartment""rental")apartmentrental("apartment""purchase")apartmentpurchase that' some pretty funny looking code this is dictionarywhere the keys are tuples of two distinct stringsand the values are class objects class objectsyesclasses can be passed aroundrenamedand stored in containers just like normal objects or primitive data types with this simple dictionarywe can simply hijack our earlier get_valid_input method to ensure we get the correct dictionary keys and look up the appropriate classlike thisdef add_property(self)property_type get_valid_input"what type of property"("house""apartment")lower(payment_type get_valid_input"what payment type"("purchase""rental")lower(propertyclass self type_map(property_typepayment_type)init_args propertyclass prompt_init(self property_list append(propertyclass(**init_args)this may look bit funny toowe look up the class in the dictionary and store it in variable named propertyclass we don' know exactly which class is availablebut the class knows itselfso we can polymorphically call prompt_init to get dictionary of values appropriate to pass into the constructor then we use the keyword argument syntax to convert the dictionary into arguments and construct the new object to load the correct data now our user can use this agent class to add and view lists of properties it wouldn' take much work to add features to mark property as available or unavailable or to edit and remove properties our prototype is now in good enough state to take to real estate agent and demonstrate its functionality here' how demo session might workagent agent(agent add_property(what type of propertywhat payment type(houseapartmenthouse (purchaserentalrental enter the square feet enter number of bedrooms enter number of bathsone and half |
3,325 | is the yard fenced(yesnoyes is there garage(attacheddetachednonedetached how many stories what is the monthly rent what are the estimated utilitiesincluded is the property furnished(yesnono agent add_property(what type of propertywhat payment type(houseapartmentapartment (purchaserentalpurchase enter the square feet enter number of bedrooms enter number of baths what laundry facilities does the property have(coinensuiteoneensuite does the property have balcony(yesnosolariumyes what is the selling price$ , what are the estimated taxes agent display_properties(property details ===============square footage bedrooms bathroomsone and half house details of stories garagedetached fenced yardyes rental details rent estimated utilitiesincluded furnishedno property details ===============square footage bedrooms |
3,326 | bathrooms apartment details laundryensuite has balconyyes purchase details selling price$ , estimated taxes exercises look around you at some of the physical objects in your workspace and see if you can describe them in an inheritance hierarchy humans have been dividing the world into taxonomies like this for centuriesso it shouldn' be difficult are there any non-obvious inheritance relationships between classes of objectsif you were to model these objects in computer applicationwhat properties and methods would they sharewhich ones would have to be polymorphically overriddenwhat properties would be completely different between themnowwrite some code nonot for the physical hierarchythat' boring physical items have more properties than methods just think about pet programming project you've wanted to tackle in the past yearbut never got around to for whatever problem you want to solvetry to think of some basic inheritance relationships then implement them make sure that you also pay attention to the sorts of relationships that you actually don' need to use inheritance for are there any places where you might want to use multiple inheritanceare you surecan you see any place you would want to use mixintry to knock together quick prototype it doesn' have to be useful or even partially working you've seen how you can test code using python - alreadyjust write some code and test it in the interactive interpreter if it workswrite some more if it doesn'tfix itnowtake look at the real estate example this turned out to be quite an effective use of multiple inheritance have to admit thoughi had my doubts when started the design have look at the original problem and see if you can come up with another design to solve it that uses only single inheritance how would you do it with abstract base classeswhat about design that doesn' use inheritance at allwhich do you think is the most elegant solutionelegance is primary goal in python developmentbut each programmer has different opinion as to what is the most elegant solution some people tend to think and understand problems most clearly using compositionwhile others find multiple inheritance to be the most useful model |
3,327 | finallytry adding some new features to the three designs whatever features strike your fancy are fine ' like to see way to differentiate between available and unavailable propertiesfor starters it' not of much use to me if it' already rentedwhich design is easiest to extendwhich is hardestif somebody asked you why you thought thiswould you be able to explain yourselfsummary we've gone from simple inheritanceone of the most useful tools in the object-oriented programmer' toolboxall the way through to multiple inheritanceone of the most complicated inheritance can be used to add functionality to existing classes and builtins using inheritance abstracting similar code into parent class can help increase maintainability methods on parent classes can be called using super and argument lists must be formatted safely for these calls to work when using multiple inheritance in the next we'll cover the subtle art of handling exceptional circumstances |
3,328 | programs are very fragile it would be ideal if code always returned valid resultbut sometimes valid result can' be calculated for exampleit' not possible to divide by zeroor to access the eighth item in five-item list in the old daysthe only way around this was to rigorously check the inputs for every function to make sure they made sense typicallyfunctions had special return values to indicate an error conditionfor examplethey could return negative number to indicate that positive value couldn' be calculated different numbers might mean different errors occurred any code that called this function would have to explicitly check for an error condition and act accordingly lot of code didn' bother to do thisand programs simply crashed howeverin the object-oriented worldthis is not the case in this we will study exceptionsspecial error objects that only need to be handled when it makes sense to handle them in particularwe will coverhow to cause an exception to occur how to recover when an exception has occurred how to handle different exception types in different ways cleaning up when an exception has occurred creating new types of exception using the exception syntax for flow control |
3,329 | raising exceptions in principlean exception is just an object there are many different exception classes availableand we can easily define more of our own the one thing they all have in common is that they inherit from built-in class called baseexception these exception objects become special when they are handled inside the program' flow of control when an exception occurseverything that was supposed to happen doesn' happenunless it was supposed to happen when an exception occurred make sensedon' worryit willthe easiest way to cause an exception to occur is to do something sillychances are you've done this already and seen the exception output for exampleany time python encounters line in your program that it can' understandit bails with syntaxerrorwhich is type of exception here' common oneprint "hello worldfile ""line print "hello worldsyntaxerrorinvalid syntax this print statement was valid command in python and previous versionsbut in python because print is now functionwe have to enclose the arguments in parenthesis soif we type the preceding command into python interpreterwe get the syntaxerror in addition to syntaxerrorsome other common exceptionswhich we can handleare shown in the following examplex traceback (most recent call last)file ""line in zerodivisionerrorint division or modulo by zero lst [ , , print(lst[ ]traceback (most recent call last)file ""line in indexerrorlist index out of range lst traceback (most recent call last) |
3,330 | file ""line in typeerrorcan only concatenate list (not "int"to list lst add traceback (most recent call last)file ""line in attributeerror'listobject has no attribute 'addd {' ''hello' [' 'traceback (most recent call last)file ""line in keyerror'bprint(this_is_not_a_vartraceback (most recent call last)file ""line in nameerrorname 'this_is_not_a_varis not defined sometimes these exceptions are indicators of something wrong in our program (in which case we would go to the indicated line number and fix it)but they also occur in legitimate situations zerodivisionerror doesn' always mean we received an invalid input it could also mean we have received different input the user may have entered zero by mistakeor on purposeor it may represent legitimate valuesuch as an empty bank account or the age of newborn child you may have noticed all the preceding built-in exceptions end with the name error in pythonthe words error and exception are used almost interchangeably errors are sometimes considered more dire than exceptionsbut they are dealt with in exactly the same way indeedall the error classes in the preceding example have exception (which extends baseexceptionas their superclass raising an exception we'll get to handling exceptions in minutebut firstlet' discover what we should do if we're writing program that needs to inform the user or calling function that the inputs are somehow invalid wouldn' it be great if we could use the same mechanism that python useswellwe canhere' simple class that adds items to list only if they are even numbered integers |
3,331 | class evenonly(list)def append(selfinteger)if not isinstance(integerint)raise typeerror("only integers can be added"if integer raise valueerror("only even numbers can be added"super(append(integerthis class extends the list built-inas we discussed in objects in pythonand overrides the append method to check two conditions that ensure the item is an even integer we first check if the input is an instance of the int typeand then use the modulus operator to ensure it is divisible by two if either of the two conditions is not metthe raise keyword causes an exception to occur the raise keyword is simply followed by the object being raised as an exception in the preceding exampletwo objects are newly constructed from the built-in classes typeerror and valueerror the raised object could just as easily be an instance of new exception class we create ourselves (we'll see how shortly)an exception that was defined elsewhereor even an exception object that has been previously raised and handled if we test this class in the python interpreterwe can see that it is outputting useful error information when exceptions occurjust as beforee evenonly( append(" string"traceback (most recent call last)file ""line in file "even_integers py"line in add raise typeerror("only integers can be added"typeerroronly integers can be added append( traceback (most recent call last)file ""line in file "even_integers py"line in add raise valueerror("only even numbers can be added"valueerroronly even numbers can be added append( |
3,332 | while this class is effective for demonstrating exceptions in actionit isn' very good at its job it is still possible to get other values into the list using index notation or slice notation this can all be avoided by overriding other appropriate methodssome of which are double-underscore methods the effects of an exception when an exception is raisedit appears to stop program execution immediately any lines that were supposed to run after the exception is raised are not executedand unless the exception is dealt withthe program will exit with an error message take look at this simple functiondef no_return()print(" am about to raise an exception"raise exception("this is always raised"print("this line will never execute"return " won' be returnedif we execute this functionwe see that the first print call is executed and then the exception is raised the second print statement is never executedand the return statement never executes eitherno_return( am about to raise an exception traceback (most recent call last)file ""line in file "exception_quits py"line in no_return raise exception("this is always raised"exceptionthis is always raised furthermoreif we have function that calls another function that raises an exceptionnothing will be executed in the first function after the point where the second function was called raising an exception stops all execution right up through the function call stack until it is either handled or forces the interpreter to exit to demonstratelet' add second function that calls the earlier onedef call_exceptor()print("call_exceptor starts here "no_return(print("an exception was raised "print(so these lines don' run" |
3,333 | when we call this functionwe see that the first print statement executesas well as the first line in the no_return function but once the exception is raisednothing else executescall_exceptor(call_exceptor starts here am about to raise an exception traceback (most recent call last)file ""line in file "method_calls_excepting py"line in call_exceptor no_return(file "method_calls_excepting py"line in no_return raise exception("this is always raised"exceptionthis is always raised we'll soon see that when the interpreter is not actually taking shortcut and exiting immediatelywe can react to and deal with the exception inside either method indeedexceptions can be handled at any level after they are initially raised look at the exception' output (called tracebackfrom bottom to topand notice how both methods are listed inside no_returnthe exception is initially raised thenjust above thatwe see that inside call_exceptorthat pesky no_return function was called and the exception bubbled up to the calling method from thereit went up one more level to the main interpreterwhichnot knowing what else to do with itgave up and printed traceback handling exceptions now let' look at the tail side of the exception coin if we encounter an exception situationhow should our code react to or recover from itwe handle exceptions by wrapping any code that might throw one (whether it is exception code itselfor call to any function or method that may have an exception raised inside itinside try except clause the most basic syntax looks like thistryno_return(exceptprint(" caught an exception"print("executed after the exception" |
3,334 | if we run this simple script using our existing no_return functionwhich as we know very wellalways throws an exceptionwe get this outputi am about to raise an exception caught an exception executed after the exception the no_return function happily informs us that it is about to raise an exceptionbut we fooled it and caught the exception once caughtwe were able to clean up after ourselves (in this caseby outputting that we were handling the situation)and continue on our waywith no interference from that offensive function the remainder of the code in the no_return function still went unexecutedbut the code that called the function was able to recover and continue note the indentation around try and except the try clause wraps any code that might throw an exception the except clause is then back on the same indentation level as the try line any code to handle the exception is indented after the except clause then normal code resumes at the original indentation level the problem with the preceding code is that it will catch any type of exception what if we were writing some code that could raise both typeerror and zerodivisionerrorwe might want to catch the zerodivisionerrorbut let the typeerror propagate to the console can you guess the syntaxhere' rather silly function that does just thatdef funny_division(divider)tryreturn divider except zerodivisionerrorreturn "zero is not good idea!print(funny_division( )print(funny_division( )print(funny_division("hello")the function is tested with print statements that show it behaving as expectedzero is not good idea traceback (most recent call last)file "catch_specific_exception py"line in print(funny_division("hello")file "catch_specific_exception py"line in funny_division return anumber typeerrorunsupported operand type(sfor /'intand 'str |
3,335 | the first line of output shows that if we enter we get properly mocked if we call with valid number (note that it' not an integerbut it' still valid divisor)it operates correctly yet if we enter string (you were wondering how to get typeerrorweren' you?)it fails with an exception if we had used an empty except clause that didn' specify zerodivisionerrorit would have accused us of dividing by zero when we sent it stringwhich is not proper behavior at all we can even catch two or more different exceptions and handle them with the same code here' an example that raises three different types of exception it handles typeerror and zerodivisionerror with the same exception handlerbut it may also raise valueerror if you supply the number def funny_division (anumber)tryif anumber = raise valueerror(" is an unlucky number"return anumber except (zerodivisionerrortypeerror)return "enter number other than zerofor val in ( "hello" )print("testing {}:format(val)end="print(funny_division (val)the for loop at the bottom loops over several test inputs and prints the results if you're wondering about that end argument in the print statementit just turns the default trailing newline into space so that it' joined with the output from the next line here' run of the programtesting enter number other than zero testing helloenter number other than zero testing testing traceback (most recent call last)file "catch_multiple_exceptions py"line in print(funny_division (val)file "catch_multiple_exceptions py"line in funny_division raise valueerror(" is an unlucky number"valueerror is an unlucky number |
3,336 | the number and the string are both caught by the except clauseand suitable error message is printed the exception from the number is not caught because it is valueerrorwhich was not included in the types of exceptions being handled this is all well and goodbut what if we want to catch different exceptions and do different things with themor maybe we want to do something with an exception and then allow it to continue to bubble up to the parent functionas if it had never been caughtwe don' need any new syntax to deal with these cases it' possible to stack except clausesand only the first match will be executed for the second questionthe raise keywordwith no argumentswill reraise the last exception if we're already inside an exception handler observe in the following codedef funny_division (anumber)tryif anumber = raise valueerror(" is an unlucky number"return anumber except zerodivisionerrorreturn "enter number other than zeroexcept typeerrorreturn "enter numerical valueexcept valueerrorprint("nononot !"raise the last line reraises the valueerrorso after outputting nononot !it will raise the exception againwe'll still get the original stack trace on the console if we stack exception clauses like we did in the preceding exampleonly the first matching clause will be runeven if more than one of them fits how can more than one clause matchremember that exceptions are objectsand can therefore be subclassed as we'll see in the next sectionmost exceptions extend the exception class (which is itself derived from baseexceptionif we catch exception before we catch typeerrorthen only the exception handler will be executedbecause typeerror is an exception by inheritance this can come in handy in cases where we want to handle some exceptions specificallyand then handle all remaining exceptions as more general case we can simply catch exception after catching all the specific exceptions and handle the general case there |
3,337 | sometimeswhen we catch an exceptionwe need reference to the exception object itself this most often happens when we define our own exceptions with custom argumentsbut can also be relevant with standard exceptions most exception classes accept set of arguments in their constructorand we might want to access those attributes in the exception handler if we define our own exception classwe can even call custom methods on it when we catch it the syntax for capturing an exception as variable uses the as keywordtryraise valueerror("this is an argument"except valueerror as eprint("the exception arguments were" argsif we run this simple snippetit prints out the string argument that we passed into valueerror upon initialization we've seen several variations on the syntax for handling exceptionsbut we still don' know how to execute code regardless of whether or not an exception has occurred we also can' specify code that should be executed only if an exception does not occur two more keywordsfinally and elsecan provide the missing pieces neither one takes any extra arguments the following example randomly picks an exception to throw and raises it then some not-so-complicated exception handling code is run that illustrates the newly introduced syntaximport random some_exceptions [valueerrortypeerrorindexerrornonetrychoice random choice(some_exceptionsprint("raising {}format(choice)if choiceraise choice("an error"except valueerrorprint("caught valueerror"except typeerrorprint("caught typeerror"except exception as eprint("caught some other error%se __class__ __name__)elseprint("this code called if there is no exception"finallyprint("this cleanup code is always called" |
3,338 | if we run this example--which illustrates almost every conceivable exception handling scenario-- few timeswe'll get different output each timedepending on which exception random chooses here are some example runspython finally_and_else py raising none this code called if there is no exception this cleanup code is always called python finally_and_else py raising caught typeerror this cleanup code is always called python finally_and_else py raising caught some other errorindexerror this cleanup code is always called python finally_and_else py raising caught valueerror this cleanup code is always called note how the print statement in the finally clause is executed no matter what happens this is extremely useful when we need to perform certain tasks after our code has finished running (even if an exception has occurredsome common examples includecleaning up an open database connection closing an open file sending closing handshake over the network the finally clause is also very important when we execute return statement from inside try clause the finally handle will still be executed before the value is returned |
3,339 | alsopay attention to the output when no exception is raisedboth the else and the finally clauses are executed the else clause may seem redundantas the code that should be executed only when no exception is raised could just be placed after the entire try except block the difference is that the else block will still be executed if an exception is caught and handled we'll see more on this when we discuss using exceptions as flow control later any of the exceptelseand finally clauses can be omitted after try block (although else by itself is invalidif you include more than onethe except clauses must come firstthen the else clausewith the finally clause at the end the order of the except clauses normally goes from most specific to most generic the exception hierarchy we've already seen several of the most common built-in exceptionsand you'll probably encounter the rest over the course of your regular python development as we noticed earliermost exceptions are subclasses of the exception class but this is not true of all exceptions exception itself actually inherits from class called baseexception in factall exceptions must extend the baseexception class or one of its subclasses there are two key exceptionssystemexit and keyboardinterruptthat derive directly from baseexception instead of exception the systemexit exception is raised whenever the program exits naturallytypically because we called the sys exit function somewhere in our code (for examplewhen the user selected an exit menu itemclicked the "closebutton on windowor entered command to shut down serverthe exception is designed to allow us to clean up code before the program ultimately exitsso we generally don' need to handle it explicitly (because cleanup code happens inside finally clauseif we do handle itwe would normally reraise the exceptionsince catching it would stop the program from exiting there areof coursesituations where we might want to stop the program exitingfor exampleif there are unsaved changes and we want to prompt the user if they really want to exit usuallyif we handle systemexit at allit' because we want to do something special with itor are anticipating it directly we especially don' want it to be accidentally caught in generic clauses that catch all normal exceptions this is why it derives directly from baseexception the keyboardinterrupt exception is common in command-line programs it is thrown when the user explicitly interrupts program execution with an os-dependent key combination (normallyctrl cthis is standard way for the user to deliberately interrupt running programand like systemexitit should almost always respond by terminating the program alsolike systemexitit should handle any cleanup tasks inside finally blocks |
3,340 | here is class diagram that fully illustrates the exception hierarchysystemexit baseexception keyboardinterrupt exception most other exception when we use the exceptclause without specifying any type of exceptionit will catch all subclasses of baseexceptionwhich is to sayit will catch all exceptionsincluding the two special ones since we almost always want these to get special treatmentit is unwise to use the exceptstatement without arguments if you want to catch all exceptions other than systemexit and keyboardinterruptexplicitly catch exception furthermoreif you do want to catch all exceptionsi suggest using the syntax except baseexceptioninstead of raw exceptthis helps explicitly tell future readers of your code that you are intentionally handling the special case exceptions defining our own exceptions oftenwhen we want to raise an exceptionwe find that none of the built-in exceptions are suitable luckilyit' trivial to define new exceptions of our own the name of the class is usually designed to communicate what went wrongand we can provide arbitrary arguments in the initializer to include additional information all we have to do is inherit from the exception class we don' even have to add any content to the classwe canof courseextend baseexception directlybut then it will not be caught by generic except exception clauses here' simple exception we might use in banking applicationclass invalidwithdrawal(exception)pass raise invalidwithdrawal("you don' have $ in your account"the last line illustrates how to raise the newly defined exception we are able to pass an arbitrary number of arguments into the exception often string message is usedbut any object that might be useful in later exception handler can be stored the exception __init__ method is designed to accept any arguments and store them as tuple in an attribute named args this makes exceptions easier to define without needing to override __init__ |
3,341 | of courseif we do want to customize the initializerwe are free to do so here' an exception whose initializer accepts the current balance and the amount the user wanted to withdraw in additionit adds method to calculate how overdrawn the request wasclass invalidwithdrawal(exception)def __init__(selfbalanceamount)super(__init__("account doesn' have ${}formatamount)self amount amount self balance balance def overage(self)return self amount self balance raise invalidwithdrawal( the raise statement at the end illustrates how to construct this exception as you can seewe can do anything with an exception that we would do with other objects we could catch an exception and pass it around as working objectalthough it is more common to include reference to the working object as an attribute on an exception and pass that around instead here' how we would handle an invalidwithdrawal exception if one was raisedtryraise invalidwithdrawal( except invalidwithdrawal as eprint(" ' sorrybut your withdrawal is "more than your balance by "${}format( overage())here we see valid use of the as keyword by conventionmost python coders name the exception variable ealthoughas usualyou are free to call it exexceptionor aunt_sally if you prefer there are many reasons for defining our own exceptions it is often useful to add information to the exception or log it in some way but the utility of custom exceptions truly comes to light when creating frameworklibraryor api that is intended for access by other programmers in that casebe careful to ensure your code is raising exceptions that make sense to the client programmer they should be easy to handle and clearly describe what went on the client programmer should easily see how to fix the error (if it reflects bug in their codeor handle the exception (if it' situation they need to be made aware of |
3,342 | exceptions aren' exceptional novice programmers tend to think of exceptions as only useful for exceptional circumstances howeverthe definition of exceptional circumstances can be vague and subject to interpretation consider the following two functionsdef divide_with_exception(numberdivisor)tryprint("{{{}formatnumberdivisornumber divisor )except zerodivisionerrorprint("you can' divide by zero"def divide_with_if(numberdivisor)if divisor = print("you can' divide by zero"elseprint("{{{}formatnumberdivisornumber divisor )these two functions behave identically if divisor is zeroan error message is printedotherwisea message printing the result of division is displayed we could avoid zerodivisionerror ever being thrown by testing for it with an if statement similarlywe can avoid an indexerror by explicitly checking whether or not the parameter is within the confines of the listand keyerror by checking if the key is in dictionary but we shouldn' do this for one thingwe might write an if statement that checks whether or not the index is lower than the parameters of the listbut forget to check negative values rememberpython lists support negative indexing- refers to the last element in the list eventuallywe would discover this and have to find all the places where we were checking code but if we had simply caught the indexerror and handled itour code would just work |
3,343 | python programmers tend to follow model of ask forgiveness rather than permissionwhich is to saythey execute code and then deal with anything that goes wrong the alternativeto look before you leapis generally frowned upon there are few reasons for thisbut the main one is that it shouldn' be necessary to burn cpu cycles looking for an unusual situation that is not going to arise in the normal path through the code thereforeit is wise to use exceptions for exceptional circumstanceseven if those circumstances are only little bit exceptional taking this argument furtherwe can actually see that the exception syntax is also effective for flow control like an if statementexceptions can be used for decision makingbranchingand message passing imagine an inventory application for company that sells widgets and gadgets when customer makes purchasethe item can either be availablein which case the item is removed from inventory and the number of items left is returnedor it might be out of stock nowbeing out of stock is perfectly normal thing to happen in an inventory application it is certainly not an exceptional circumstance but what do we return if it' out of stocka string saying out of stocka negative numberin both casesthe calling method would have to check whether the return value is positive integer or something elseto determine if it is out of stock that seems bit messy insteadwe can raise outofstockexception and use the try statement to direct program flow control make sensein additionwe want to make sure we don' sell the same item to two different customersor sell an item that isn' in stock yet one way to facilitate this is to lock each type of item to ensure only one person can update it at time the user must lock the itemmanipulate the item (purchaseadd stockcount items left )and then unlock the item here' an incomplete inventory example with docstrings that describes what some of the methods should doclass inventorydef lock(selfitem_type)'''select the type of item that is going to be manipulated this method will lock the item so nobody else can manipulate the inventory until it' returned this prevents selling the same item to two different customers ''pass def unlock(selfitem_type)'''release the given type so that other customers can access it ''pass def purchase(selfitem_type) |
3,344 | '''if the item is not lockedraise an exception if the item_type does not existraise an exception if the item is currently out of stockraise an exception if the item is availablesubtract one item and return the number of items left ''pass we could hand this object prototype to developer and have them implement the methods to do exactly as they say while we work on the code that needs to make purchase we'll use python' robust exception handling to consider different branchesdepending on how the purchase was madeitem_type 'widgetinv inventory(inv lock(item_typetrynum_left inv purchase(item_typeexcept invaliditemtypeprint("sorrywe don' sell {}format(item_type)except outofstockprint("sorrythat item is out of stock "elseprint("purchase complete there are "{{} leftformat(num_leftitem_type)finallyinv unlock(item_typepay attention to how all the possible exception handling clauses are used to ensure the correct actions happen at the correct time even though outofstock is not terribly exceptional circumstancewe are able to use an exception to handle it suitably this same code could be written with an if elif else structurebut it wouldn' be as easy to read or maintain we can also use exceptions to pass messages between different methods for exampleif we wanted to inform the customer as to what date the item is expected to be in stock againwe could ensure our outofstock object requires back_in_stock parameter when it is constructed thenwhen we handle the exceptionwe can check that value and provide additional information to the customer the information attached to the object can be easily passed between two different parts of the program the exception could even provide method that instructs the inventory object to reorder or backorder an item |
3,345 | using exceptions for flow control can make for some handy program designs the important thing to take from this discussion is that exceptions are not bad thing that we should try to avoid having an exception occur does not mean that you should have prevented this exceptional circumstance from happening ratherit is just powerful way to communicate information between two sections of code that may not be directly calling each other case study we've been looking at the use and handling of exceptions at fairly low level of detail--syntax and definitions this case study will help tie it all in with our previous so we can see how exceptions are used in the larger context of objectsinheritanceand modules todaywe'll be designing simple central authentication and authorization system the entire system will be placed in one moduleand other code will be able to query that module object for authentication and authorization purposes we should admitfrom the startthat we aren' security expertsand that the system we are designing may be full of security holes our purpose is to study exceptionsnot to secure system it will be sufficienthoweverfor basic login and permission system that other code can interact with laterif that other code needs to be made more securewe can have security or cryptography expert review or rewrite our modulepreferably without changing the api authentication is the process of ensuring user is really the person they say they are we'll follow the lead of common web systems todaywhich use username and private password combination other methods of authentication include voice recognitionfingerprint or retinal scannersand identification cards authorizationon the other handis all about determining whether given (authenticateduser is permitted to perform specific action we'll create basic permission list system that stores list of the specific people allowed to perform each action in additionwe'll add some administrative features to allow new users to be added to the system for brevitywe'll leave out editing of passwords or changing of permissions once they've been addedbut these (highly necessaryfeatures can certainly be added in the future |
3,346 | there' simple analysisnow let' proceed with design we're obviously going to need user class that stores the username and an encrypted password this class will also allow user to log in by checking whether supplied password is valid we probably won' need permission classas those can just be strings mapped to list of users using dictionary we should have central authenticator class that handles user management and logging in or out the last piece of the puzzle is an authorizor class that deals with permissions and checking whether user can perform an activity we'll provide single instance of each of these classes in the auth module so that other modules can use this central mechanism for all their authentication and authorization needs of courseif they want to instantiate private instances of these classesfor non-central authorization activitiesthey are free to do so we'll also be defining several exceptions as we go along we'll start with special authexception base class that accepts username and optional user object as parametersmost of our self-defined exceptions will inherit from this one let' build the user class firstit seems simple enough new user can be initialized with username and password the password will be stored encrypted to reduce the chances of its being stolen we'll also need check_password method to test whether supplied password is the correct one here is the class in fullimport hashlib class userdef __init__(selfusernamepassword)'''create new user object the password will be encrypted before storing ''self username username self password self _encrypt_pw(passwordself is_logged_in false def _encrypt_pw(selfpassword)'''encrypt the password with the username and return the sha digest ''hash_string (self username passwordhash_string hash_string encode("utf "return hashlib sha (hash_stringhexdigest(def check_password(selfpassword)'''return true if the password is valid for this userfalse otherwise ''encrypted self _encrypt_pw(passwordreturn encrypted =self password |
3,347 | since the code for encrypting password is required in both __init__ and check_ passwordwe pull it out to its own method this wayit only needs to be changed in one place if someone realizes it is insecure and needs improvement this class could easily be extended to include mandatory or optional personal detailssuch as namescontact informationand birth dates before we write code to add users (which will happen in the as-yet undefined authenticator class)we should examine some use cases if all goes wellwe can add user with username and passwordthe user object is created and inserted into dictionary but in what ways can all not go wellwellclearly we don' want to add user with username that already exists in the dictionary if we did sowe' overwrite an existing user' data and the new user might have access to that user' privileges sowe'll need usernamealreadyexists exception alsofor security' sakewe should probably raise an exception if the password is too short both of these exceptions will extend authexceptionwhich we mentioned earlier sobefore writing the authenticator classlet' define these three exception classesclass authexception(exception)def __init__(selfusernameuser=none)super(__init__(usernameuserself username username self user user class usernamealreadyexists(authexception)pass class passwordtooshort(authexception)pass the authexception requires username and has an optional user parameter this second parameter should be an instance of the user class associated with that username the two specific exceptions we're defining simply need to inform the calling class of an exceptional circumstanceso we don' need to add any extra methods to them now let' start on the authenticator class it can simply be mapping of usernames to user objectsso we'll start with dictionary in the initialization function the method for adding user needs to check the two conditions (password length and previously existing usersbefore creating new user instance and adding it to the dictionaryclass authenticatordef __init__(self)'''construct an authenticator to manage |
3,348 | users logging in and out ''self users {def add_user(selfusernamepassword)if username in self usersraise usernamealreadyexists(usernameif len(password raise passwordtooshort(usernameself users[usernameuser(usernamepasswordwe couldof courseextend the password validation to raise exceptions for passwords that are too easy to crack in other waysif we desired now let' prepare the login method if we weren' thinking about exceptions just nowwe might just want the method to return true or falsedepending on whether the login was successful or not but we are thinking about exceptionsand this could be good place to use them for not-so-exceptional circumstance we could raise different exceptionsfor exampleif the username does not exist or the password does not match this will allow anyone trying to log user in to elegantly handle the situation using try/except/else clause sofirst we add these new exceptionsclass invalidusername(authexception)pass class invalidpassword(authexception)pass then we can define simple login method to our authenticator class that raises these exceptions if necessary if notit flags the user as logged in and returnsdef login(selfusernamepassword)tryuser self users[usernameexcept keyerrorraise invalidusername(usernameif not user check_password(password)raise invalidpassword(usernameuseruser is_logged_in true return true notice how the keyerror is handled this could have been handled using if username not in self usersinsteadbut we chose to handle the exception directly we end up eating up this first exception and raising brand new one of our own that better suits the user-facing api |
3,349 | we can also add method to check whether particular username is logged in deciding whether to use an exception here is trickier should we raise an exception if the username does not existshould we raise an exception if the user is not logged into answer these questionswe need to think about how the method would be accessed most oftenthis method will be used to answer the yes/no question"should allow them access to ?the answer will either be"yesthe username is valid and they are logged in"or "nothe username is not valid or they are not logged inthereforea boolean return value is sufficient there is no need to use exceptions herejust for the sake of using an exception def is_logged_in(selfusername)if username in self usersreturn self users[usernameis_logged_in return false finallywe can add default authenticator instance to our module so that the client code can access it easily using auth authenticatorauthenticator authenticator(this line goes at the module leveloutside any class definitionso the authenticator variable can be accessed as auth authenticator now we can start on the authorizor classwhich maps permissions to users the authorizor class should not permit user access to permission if they are not logged inso they'll need reference to specific authenticator we'll also need to set up the permission dictionary upon initializationclass authorizordef __init__(selfauthenticator)self authenticator authenticator self permissions {now we can write methods to add new permissions and to set up which users are associated with each permissiondef add_permission(selfperm_name)'''create new permission that users can be added to''tryperm_set self permissions[perm_nameexcept keyerrorself permissions[perm_nameset(else |
3,350 | raise permissionerror("permission exists"def permit_user(selfperm_nameusername)'''grant the given permission to the user''tryperm_set self permissions[perm_nameexcept keyerrorraise permissionerror("permission does not exist"elseif username not in self authenticator usersraise invalidusername(usernameperm_set add(usernamethe first method allows us to create new permissionunless it already existsin which case an exception is raised the second allows us to add username to permissionunless either the permission or the username doesn' yet exist we use set instead of list for usernamesso that even if you grant user permission more than oncethe nature of sets means the user is only in the set once we'll discuss sets further in later permissionerror is raised in both methods this new error doesn' require usernameso we'll make it extend exception directlyinstead of our custom authexceptionclass permissionerror(exception)pass finallywe can add method to check whether user has specific permission or not in order for them to be granted accessthey have to be both logged into the authenticator and in the set of people who have been granted access to that privilege if either of these conditions is unsatisfiedan exception is raiseddef check_permission(selfperm_nameusername)if not self authenticator is_logged_in(username)raise notloggedinerror(usernametryperm_set self permissions[perm_nameexcept keyerrorraise permissionerror("permission does not exist"elseif username not in perm_setraise notpermittederror(usernameelsereturn true |
3,351 | there are two new exceptions in herethey both take usernamesso we'll define them as subclasses of authexceptionclass notloggedinerror(authexception)pass class notpermittederror(authexception)pass finallywe can add default authorizor to go with our default authenticatorauthorizor authorizor(authenticatorthat completes basic authentication/authorization system we can test the system at the python promptchecking to see whether userjoeis permitted to do tasks in the paint departmentimport auth auth authenticator add_user("joe""joepassword"auth authorizor add_permission("paint"auth authorizor check_permission("paint""joe"traceback (most recent call last)file ""line in file "auth py"line in check_permission raise notloggedinerror(usernameauth notloggedinerrorjoe auth authenticator is_logged_in("joe"false auth authenticator login("joe""joepassword"true auth authorizor check_permission("paint""joe"traceback (most recent call last)file ""line in file "auth py"line in check_permission raise notpermittederror(usernameauth notpermittederrorjoe auth authorizor check_permission("mix""joe"traceback (most recent call last)file "auth py"line in check_permission perm_set self permissions[perm_name |
3,352 | keyerror'mixduring handling of the above exceptionanother exception occurredtraceback (most recent call last)file ""line in file "auth py"line in check_permission raise permissionerror("permission does not exist"auth permissionerrorpermission does not exist auth authorizor permit_user("mix""joe"traceback (most recent call last)file "auth py"line in permit_user perm_set self permissions[perm_namekeyerror'mixduring handling of the above exceptionanother exception occurredtraceback (most recent call last)file ""line in file "auth py"line in permit_user raise permissionerror("permission does not exist"auth permissionerrorpermission does not exist auth authorizor permit_user("paint""joe"auth authorizor check_permission("paint""joe"true while verbosethe preceding output shows all of our code and most of our exceptions in actionbut to really understand the api we've definedwe should write some exception handling code that actually uses it here' basic menu interface that allows certain users to change or test programimport auth set up test user and permission auth authenticator add_user("joe""joepassword"auth authorizor add_permission("test program"auth authorizor add_permission("change program"auth authorizor permit_user("test program""joe"class editor |
3,353 | def __init__(self)self username none self menu_map "login"self login"test"self test"change"self change"quit"self quit def login(self)logged_in false while not logged_inusername input("username"password input("password"trylogged_in auth authenticator loginusernamepasswordexcept auth invalidusernameprint("sorrythat username does not exist"except auth invalidpasswordprint("sorryincorrect password"elseself username username def is_permitted(selfpermission)tryauth authorizor check_permissionpermissionself usernameexcept auth notloggedinerror as eprint("{is not logged informat( username)return false except auth notpermittederror as eprint("{cannot {}formate usernamepermission)return false elsereturn true def test(self)if self is_permitted("test program")print("testing program now "def change(self)if self is_permitted("change program")print("changing program now "def quit(self) |
3,354 | raise systemexit(def menu(self)tryanswer "while trueprint(""please enter command\tlogin\tlogin \ttest\ttest the program \tchange\tchange the program \tquit\tquit """answer input("enter command"lower(tryfunc self menu_map[answerexcept keyerrorprint("{is not valid optionformatanswer)elsefunc(finallyprint("thank you for testing the auth module"editor(menu(this rather long example is conceptually very simple the is_permitted method is probably the most interestingthis is mostly internal method that is called by both test and change to ensure the user is permitted access before continuing of coursethose two methods are stubsbut we aren' writing an editor herewe're illustrating the use of exceptions and exception handlers by testing an authentication and authorization frameworkexercises if you've never dealt with exceptions beforethe first thing you need to do is look at any old python code you've written and notice if there are places you should have been handling exceptions how would you handle themdo you need to handle them at allsometimesletting the exception propagate to the console is the best way to communicate to the userespecially if the user is also the script' coder sometimesyou can recover from the error and allow the program to continue sometimesyou can only reformat the error into something the user can understand and display it to them |
3,355 | some common places to look are file / (is it possible your code will try to read file that doesn' exist?)mathematical expressions (is it possible that value you are dividing by is zero?)list indices (is the list empty?)and dictionaries (does the key exist?ask yourself if you should ignore the problemhandle it by checking values firstor handle it with an exception pay special attention to areas where you might have used finally and else to ensure the correct code is executed under all conditions now write some new code think of program that requires authentication and authorizationand try writing some code that uses the auth module we built in the case study feel free to modify the module if it' not flexible enough try to handle all the exceptions in sensible way if you're having trouble coming up with something that requires authenticationtry adding authorization to the notepad example from objects in pythonor add authorization to the auth module itself--it' not terribly useful module if just anybody can start adding permissionsmaybe require an administrator username and password before allowing privileges to be added or changed finallytry to think of places in your code where you can raise exceptions it can be in code you've written or are working onor you can write new project as an exercise you'll probably have the best luck for designing small framework or api that is meant to be used by other peopleexceptions are terrific communication tool between your code and someone else' remember to design and document any self-raised exceptions as part of the apior they won' know whether or how to handle themsummary in this we went into the gritty details of raisinghandlingdefiningand manipulating exceptions exceptions are powerful way to communicate unusual circumstances or error conditions without requiring calling function to explicitly check return values there are many built-in exceptions and raising them is trivially easy there are several different syntaxes for handling different exception events in the next everything we've studied so far will come together as we discuss how object-oriented programming principles and structures should best be applied in python applications |
3,356 | programming in previous we've covered many of the defining features of object-oriented programming we now know the principles and paradigms of object-oriented designand we've covered the syntax of object-oriented programming in python yetwe don' know exactly how and when to utilize these principles and syntax in practice in this we'll discuss some useful applications of the knowledge we've gainedpicking up some new topics along the wayhow to recognize objects data and behaviorsonce again wrapping data in behavior using properties restricting data using behavior the don' repeat yourself principle recognizing repeated code treat objects as objects this may seem obviousyou should generally give separate objects in your problem domain special class in your code we've seen examples of this in the case studies in previous firstwe identify objects in the problem and then model their data and behaviors |
3,357 | identifying objects is very important task in object-oriented analysis and programming but it isn' always as easy as counting the nouns in short paragraphas we've been doing rememberobjects are things that have both data and behavior if we are working only with datawe are often better off storing it in listsetdictionaryor some other python data structure (which we'll be covering thoroughly in python data structureson the other handif we are working only with behaviorbut no stored dataa simple function is more suitable an objecthoweverhas both data and behavior proficient python programmers use built-in data structures unless (or untilthere is an obvious need to define class there is no reason to add an extra level of abstraction if it doesn' help organize our code on the other handthe "obviousneed is not always self-evident we can often start our python programs by storing data in few variables as the program expandswe will later find that we are passing the same set of related variables to set of functions this is the time to think about grouping both variables and functions into class if we are designing program to model polygons in twodimensional spacewe might start with each polygon being represented as list of points the points would be modeled as two-tuples (xydescribing where that point is located this is all datastored in set of nested data structures (specificallya list of tuples)square [( , )( , )( , )( , )nowif we want to calculate the distance around the perimeter of the polygonwe simply need to sum the distances between the two points to do thiswe also need function to calculate the distance between two points here are two such functionsimport math def distance( )return math sqrt(( [ ]- [ ])** ( [ ]- [ ])** def perimeter(polygon)perimeter points polygon [polygon[ ]for in range(len(polygon))perimeter +distance(points[ ]points[ + ]return perimeter nowas object-oriented programmerswe clearly recognize that polygon class could encapsulate the list of points (dataand the perimeter function (behaviorfurthera point classsuch as we defined in objects in pythonmight encapsulate the and coordinates and the distance method the question isis it valuable to do this |
3,358 | for the previous codemaybe yesmaybe no with our recent experience in object-oriented principleswe can write an object-oriented version in record time let' compare them import math class pointdef __init__(selfxy)self self def distance(selfp )return math sqrt((self - )** (self - )** class polygondef __init__(self)self vertices [def add_point(selfpoint)self vertices append((point)def perimeter(self)perimeter points self vertices [self vertices[ ]for in range(len(self vertices))perimeter +points[idistance(points[ + ]return perimeter as we can see from the highlighted sectionsthere is twice as much code here as there was in our earlier versionalthough we could argue that the add_point method is not strictly necessary nowto understand the differences little betterlet' compare the two apis in use here' how to calculate the perimeter of square using the object-oriented codesquare polygon(square add_point(point( , )square add_point(point( , )square add_point(point( , )square add_point(point( , )square perimeter( |
3,359 | that' fairly succinct and easy to readyou might thinkbut let' compare it to the function-based codesquare [( , )( , )( , )( , )perimeter(square hmmmaybe the object-oriented api isn' so compactthat saidi' argue that it was easier to read than the functional examplehow do we know what the list of tuples is supposed to represent in the second versionhow do we remember what kind of object ( list of two-tuplesthat' not intuitive!we're supposed to pass into the perimeter functionwe would need lot of documentation to explain how these functions should be used in contrastthe object-oriented code is relatively self-documentingwe just have to look at the list of methods and their parameters to know what the object does and how to use it by the time we wrote all the documentation for the functional versionit would probably be longer than the object-oriented code finallycode length is not good indicator of code complexity some programmers get hung up on complicated "one linersthat do an incredible amount of work in one line of code this can be fun exercisebut the result is often unreadableeven to the original author the following day minimizing the amount of code can often make program easier to readbut do not blindly assume this is the case luckilythis trade-off isn' necessary we can make the object-oriented polygon api as easy to use as the functional implementation all we have to do is alter our polygon class so that it can be constructed with multiple points let' give it an initializer that accepts list of point objects in factlet' allow it to accept tuples tooand we can construct the point objects ourselvesif neededdef __init__(selfpoints=none)points points if points else [self vertices [for point in pointsif isinstance(pointtuple)point point(*pointself vertices append(pointthis initializer goes through the list and ensures that any tuples are converted to points if the object is not tuplewe leave it as isassuming that it is either point object alreadyor an unknown duck-typed object that can act like point object |
3,360 | stillthere' no clear winner between the object-oriented and more data-oriented versions of this code they both do the same thing if we have new functions that accept polygon argumentsuch as area(polygonor point_in_polygon(polygonxy)the benefits of the object-oriented code become increasingly obvious likewiseif we add other attributes to the polygonsuch as color or textureit makes more and more sense to encapsulate that data into single class the distinction is design decisionbut in generalthe more complicated set of data isthe more likely it is to have multiple functions specific to that dataand the more useful it is to use class with attributes and methods instead when making this decisionit also pays to consider how the class will be used if we're only trying to calculate the perimeter of one polygon in the context of much greater problemusing function will probably be quickest to code and easier to use "one time onlyon the other handif our program needs to manipulate numerous polygons in wide variety of ways (calculate perimeterareaintersection with other polygonsmove or scale themand so on)we have most certainly identified an objectone that needs to be extremely versatile additionallypay attention to the interaction between objects look for inheritance relationshipsinheritance is impossible to model elegantly without classesso make sure to use them look for the other types of relationships we discussed in object-oriented designassociation and composition composition cantechnicallybe modeled using only data structuresfor examplewe can have list of dictionaries holding tuple valuesbut it is often less complicated to create few classes of objectsespecially if there is behavior associated with the data don' rush to use an object just because you can use an objectbut never neglect to create class when you need to use class adding behavior to class data with properties throughout this bookwe've been focusing on the separation of behavior and data this is very important in object-oriented programmingbut we're about to see thatin pythonthe distinction can be uncannily blurry python is very good at blurring distinctionsit doesn' exactly help us to "think outside the boxratherit teaches us to stop thinking about the box |
3,361 | before we get into the detailslet' discuss some bad object-oriented theory many object-oriented languages (java is the most notoriousteach us to never access attributes directly they insist that we write attribute access like thisclass colordef __init__(selfrgb_valuename)self _rgb_value rgb_value self _name name def set_name(selfname)self _name name def get_name(self)return self _name the variables are prefixed with an underscore to suggest that they are private (other languages would actually force them to be privatethen the get and set methods provide access to each variable this class would be used in practice as followsc color("#ff ""bright red" get_name('bright redc set_name("red" get_name('redthis is not nearly as readable as the direct access version that python favorsclass colordef __init__(selfrgb_valuename)self rgb_value rgb_value self name name color("#ff ""bright red"print( namec name "redso why would anyone insist upon the method-based syntaxtheir reasoning is that someday we may want to add extra code when value is set or retrieved for examplewe could decide to cache value and return the cached valueor we might want to validate that the value is suitable input |
3,362 | in codewe could decide to change the set_name(method as followsdef set_name(selfname)if not nameraise exception("invalid name"self _name name nowin java and similar languagesif we had written our original code to do direct attribute accessand then later changed it to method like the preceding onewe' have problemanyone who had written code that accessed the attribute directly would now have to access the method if they don' change the access style from attribute access to function calltheir code will be broken the mantra in these languages is that we should never make public members private this doesn' make much sense in python since there isn' any real concept of private memberspython gives us the property keyword to make methods look like attributes we can therefore write our code to use direct member accessand if we unexpectedly need to alter the implementation to do some calculation when getting or setting that attribute' valuewe can do so without changing the interface let' see how it looksclass colordef __init__(selfrgb_valuename)self rgb_value rgb_value self _name name def _set_name(selfname)if not nameraise exception("invalid name"self _name name def _get_name(self)return self _name name property(_get_name_set_nameif we had started with the earlier non-method-based classwhich set the name attribute directlywe could later change the code to look like the preceding one we first change the name attribute into (semi-private _name attribute then we add two more (semi-private methods to get and set that variabledoing our validation when we set it |
3,363 | finallywe have the property declaration at the bottom this is the magic it creates new attribute on the color class called namewhich now replaces the previous name attribute it sets this attribute to be propertywhich calls the two methods we just created whenever the property is accessed or changed this new version of the color class can be used exactly the same way as the previous versionyet it now does validation when we set the name attributec color("# ff""bright red"print( namebright red name "redprint( namered name "traceback (most recent call last)file ""line in file "setting_name_property py"line in _set_name raise exception("invalid name"exceptioninvalid name soif we' previously written code to access the name attributeand then changed it to use our property objectthe previous code would still workunless it was sending an empty property valuewhich is the behavior we wanted to forbid in the first place successbear in mind that even with the name propertythe previous code is not percent safe people can still access the _name attribute directly and set it to an empty string if they want to but if they access variable we've explicitly marked with an underscore to suggest it is privatethey're the ones that have to deal with the consequencesnot us properties in detail think of the property function as returning an object that proxies any requests to set or access the attribute value through the methods we have specified the property keyword is like constructor for such an objectand that object is set as the public facing member for the given attribute |
3,364 | this property constructor can actually accept two additional argumentsa deletion function and docstring for the property the delete function is rarely supplied in practicebut it can be useful for logging that value has been deletedor possibly to veto deleting if we have reason to do so the docstring is just string describing what the property doesno different from the docstrings we discussed in objects in python if we do not supply this parameterthe docstring will instead be copied from the docstring for the first argumentthe getter method here is silly example that simply states whenever any of the methods are calledclass sillydef _get_silly(self)print("you are getting silly"return self _silly def _set_silly(selfvalue)print("you are making silly {}format(value)self _silly value def _del_silly(self)print("whoahyou killed silly!"del self _silly silly property(_get_silly_set_silly_del_silly"this is silly property"if we actually use this classit does indeed print out the correct strings when we ask it tos silly( silly "funnyyou are making silly funny silly you are getting silly 'funnydel silly whoahyou killed sillyfurtherif we look at the help file for the silly class (by issuing help(sillyat the interpreter prompt)it shows us the custom docstring for our silly attributehelp on class silly in module __main__class silly(builtins object |
3,365 | data descriptors defined here__dict__ dictionary for instance variables (if defined__weakref__ list of weak references to the object (if definedsilly this is silly property once againeverything is working as we planned in practiceproperties are normally only defined with the first two parametersthe getter and setter functions if we want to supply docstring for propertywe can define it on the getter functionthe property proxy will copy it into its own docstring the deletion function is often left empty because object attributes are rarely deleted if coder does try to delete property that doesn' have deletion function specifiedit will raise an exception thereforeif there is legitimate reason to delete our propertywe should supply that function decorators another way to create properties if you've never used python decorators beforeyou might want to skip this section and come back to it after we've discussed the decorator pattern in python design patterns howeveryou don' need to understand what' going on to use the decorator syntax to make property methods more readable the property function can be used with the decorator syntax to turn get function into propertyclass foo@property def foo(self)return "barthis applies the property function as decoratorand is equivalent to the previous foo property(foosyntax the main differencefrom readability perspectiveis that we get to mark the foo function as property at the top of the methodinstead of after it is definedwhere it can be easily overlooked it also means we don' have to create private methods with underscore prefixes just to define property |
3,366 | going one step furtherwe can specify setter function for the new property as followsclass foo@property def foo(self)return self _foo @foo setter def foo(selfvalue)self _foo value this syntax looks pretty oddalthough the intent is obvious firstwe decorate the foo method as getter thenwe decorate second method with exactly the same name by applying the setter attribute of the originally decorated foo methodthe property function returns an objectthis object always comes with its own setter attributewhich can then be applied as decorator to other functions using the same name for the get and set methods is not requiredbut it does help group the multiple methods that access one property together we can also specify deletion function with @foo deleter we cannot specify docstring using property decoratorsso we need to rely on the property copying the docstring from the initial getter method here' our previous silly class rewritten to use property as decoratorclass silly@property def silly(self)"this is silly propertyprint("you are getting silly"return self _silly @silly setter def silly(selfvalue)print("you are making silly {}format(value)self _silly value @silly deleter def silly(self)print("whoahyou killed silly!"del self _silly this class operates exactly the same as our earlier versionincluding the help text you can use whichever syntax you feel is more readable and elegant |
3,367 | deciding when to use properties with the property built-in clouding the division between behavior and datait can be confusing to know which one to choose the example use case we saw earlier is one of the most common uses of propertieswe have some data on class that we later want to add behavior to there are also other factors to take into account when deciding to use property technicallyin pythondatapropertiesand methods are all attributes on class the fact that method is callable does not distinguish it from other types of attributesindeedwe'll see in python object-oriented shortcutsthat it is possible to create normal objects that can be called like functions we'll also discover that functions and methods are themselves normal objects the fact that methods are just callable attributesand properties are just customizable attributes can help us make this decision methods should typically represent actionsthings that can be done toor performed bythe object when you call methodeven with only one argumentit should do something method names are generally verbs once confirming that an attribute is not an actionwe need to decide between standard data attributes and properties in generalalways use standard attribute until you need to control access to that property in some way in either caseyour attribute is usually noun the only difference between an attribute and property is that we can invoke custom actions automatically when property is retrievedsetor deleted let' look at more realistic example common need for custom behavior is caching value that is difficult to calculate or expensive to look up (requiringfor examplea network request or database querythe goal is to store the value locally to avoid repeated calls to the expensive calculation we can do this with custom getter on the property the first time the value is retrievedwe perform the lookup or calculation then we could locally cache the value as private attribute on our object (or in dedicated caching software)and the next time the value is requestedwe return the stored data here' how we might cache web pagefrom urllib request import urlopen class webpagedef __init__(selfurl)self url url self _content none @property |
3,368 | def content(self)if not self _contentprint("retrieving new page "self _content urlopen(self urlread(return self _content we can test this code to see that the page is only retrieved onceimport time webpage webpage(now time time(content webpage content retrieving new page time time(now now time time(content webpage content time time(now content =content true was on an awful satellite connection when originally tested this code and it took seconds the first time loaded the content the second timei got the result in seconds (which is really just the amount of time it took to type the lines into the interpretercustom getters are also useful for attributes that need to be calculated on the flybased on other object attributes for examplewe might want to calculate the average for list of integersclass averagelist(list)@property def average(self)return sum(selflen(selfthis very simple class inherits from listso we get list-like behavior for free we just add property to the classand prestoour list can have an averagea averagelist([ , , , ] average |
3,369 | of coursewe could have made this method insteadbut then we should call it calculate_average()since methods represent actions but property called average is more suitableboth easier to typeand easier to read custom setters are useful for validationas we've already seenbut they can also be used to proxy value to another location for examplewe could add content setter to the webpage class that automatically logs into our web server and uploads new page whenever the value is set manager objects we've been focused on objects and their attributes and methods nowwe'll take look at designing higher-level objectsthe kinds of objects that manage other objects the objects that tie everything together the difference between these objects and most of the examples we've seen so far is that our examples tend to represent concrete ideas management objects are more like office managersthey don' do the actual "visiblework out on the floorbut without themthere would be no communication between departments and nobody would know what they are supposed to do (althoughthis can be true anyway if the organization is badly managed!analogouslythe attributes on management class tend to refer to other objects that do the "visibleworkthe behaviors on such class delegate to those other classes at the right timeand pass messages between them as an examplewe'll write program that does find and replace action for text files stored in compressed zip file we'll need objects to represent the zip file and each individual text file (luckilywe don' have to write these classesthey're available in the python standard librarythe manager object will be responsible for ensuring three steps occur in order unzipping the compressed file performing the find and replace action zipping up the new files the class is initialized with the zip filename and search and replace strings we create temporary directory to store the unzipped files inso that the folder stays clean the python pathlib library helps out with file and directory manipulation we'll learn more about that in strings and serializationbut the interface should be pretty clear in the following exampleimport sys import shutil import zipfile |
3,370 | from pathlib import path class zipreplacedef __init__(selffilenamesearch_stringreplace_string)self filename filename self search_string search_string self replace_string replace_string self temp_directory path("unzipped-{}formatfilename)thenwe create an overall "managermethod for each of the three steps this method delegates responsibility to other methods obviouslywe could do all three steps in one methodor indeedin one script without ever creating an object there are several advantages to separating the three stepsreadabilitythe code for each step is in self-contained unit that is easy to read and understand the method names describe what the method doesand less additional documentation is required to understand what is going on extensibilityif subclass wanted to use compressed tar files instead of zip filesit could override the zip and unzip methods without having to duplicate the find_replace method partitioningan external class could create an instance of this class and call the find_replace method directly on some folder without having to zip the content the delegation method is the first in the following codethe rest of the methods are included for completenessdef zip_find_replace(self)self unzip_files(self find_replace(self zip_files(def unzip_files(self)self temp_directory mkdir(with zipfile zipfile(self filenameas zipzip extractall(str(self temp_directory)def find_replace(self)for filename in self temp_directory iterdir()with filename open(as filecontents file read(contents contents replaceself search_stringself replace_string |
3,371 | with filename open(" "as filefile write(contentsdef zip_files(self)with zipfile zipfile(self filename' 'as filefor filename in self temp_directory iterdir()file write(str(filename)filename nameshutil rmtree(str(self temp_directory)if __name__ ="__main__"zipreplace(*sys argv[ : ]zip_find_replace(for brevitythe code for zipping and unzipping files is sparsely documented our current focus is on object-oriented designif you are interested in the inner details of the zipfile modulerefer to the documentation in the standard libraryeither online or by typing import zipfile help(zipfileinto your interactive interpreter note that this example only searches the top-level files in zip fileif there are any folders in the unzipped contentthey will not be scannednor will any files inside those folders the last two lines in the example allow us to run the program from the command line by passing the zip filenamesearch stringand replace string as argumentspython zipsearch py hello zip hello hi of coursethis object does not have to be created from the command lineit could be imported from another module (to perform batch zip file processingor accessed as part of gui interface or even higher-level management object that knows where to get zip files (for exampleto retrieve them from an ftp server or back them up to an external diskas programs become more and more complexthe objects being modeled become less and less like physical objects properties are other abstract objects and methods are actions that change the state of those abstract objects but at the heart of every objectno matter how complexis set of concrete properties and well-defined behaviors removing duplicate code often the code in management style classes such as zipreplace is quite generic and can be applied in variety of ways it is possible to use either composition or inheritance to help keep this code in one placethus eliminating duplicate code before we look at any examples of thislet' discuss tiny bit of theory specificallywhy is duplicate code bad thing |
3,372 | there are several reasonsbut they all boil down to readability and maintainability when we're writing new piece of code that is similar to an earlier piecethe easiest thing to do is copy the old code and change whatever needs to be changed (variable nameslogiccommentsto make it work in the new location alternativelyif we're writing new code that seems similarbut not identical to code elsewhere in the projectit is often easier to write fresh code with similar behaviorrather than figure out how to extract the overlapping functionality but as soon as someone has to read and understand the code and they come across duplicate blocksthey are faced with dilemma code that might have made sense suddenly has to be understood how is one section different from the otherhow are they the sameunder what conditions is one section calledwhen do we call the otheryou might argue that you're the only one reading your codebut if you don' touch that code for eight months it will be as incomprehensible to you as it is to fresh coder when we're trying to read two similar pieces of codewe have to understand why they're differentas well as how they're different this wastes the reader' timecode should always be written to be readable first once had to try to understand someone' code that had three identical copies of the same lines of very poorly written code had been working with the code for month before finally comprehended that the three "identicalversions were actually performing slightly different tax calculations some of the subtle differences were intentionalbut there were also obvious areas where someone had updated calculation in one function without updating the other two the number of subtleincomprehensible bugs in the code could not be counted eventually replaced all lines with an easy-to-read function of lines or so reading such duplicate code can be tiresomebut code maintenance is even more tormenting as the preceding story suggestskeeping two similar pieces of code up to date can be nightmare we have to remember to update both sections whenever we update one of themand we have to remember how the multiple sections differ so we can modify our changes when we are editing each of them if we forget to update both sectionswe will end up with extremely annoying bugs that usually manifest themselves as"but fixed that alreadywhy is it still happening?the result is that people who are reading or maintaining our code have to spend astronomical amounts of time understanding and testing it compared to if we had written the code in nonrepetitive manner in the first place it' even more frustrating when we are the ones doing the maintenancewe find ourselves saying"why didn' do this right the first time?the time we save by copy-pasting existing code is lost the very first time we have to maintain it code is both read and modified many more times and much more often than it is written comprehensible code should always be paramount |
3,373 | this is why programmersespecially python programmers (who tend to value elegant code more than average)follow what is known as the don' repeat yourself (dryprinciple dry code is maintainable code my advice to beginning programmers is to never use the copy and paste feature of their editor to intermediate programmersi suggest they think thrice before they hit ctrl but what should we do instead of code duplicationthe simplest solution is often to move the code into function that accepts parameters to account for whatever parts are different this isn' terribly object-oriented solutionbut it is frequently optimal for exampleif we have two pieces of code that unzip zip file into two different directorieswe can easily write function that accepts parameter for the directory to which it should be unzipped instead this may make the function itself slightly more difficult to readbut good function name and docstring can easily make up for thatand any code that invokes the function will be easier to read that' certainly enough theorythe moral of the story isalways make the effort to refactor your code to be easier to read instead of writing bad code that is only easier to write in practice let' explore two ways we can reuse existing code after writing our code to replace strings in zip file full of text fileswe are later contracted to scale all the images in zip file to looks like we could use very similar paradigm to what we used in zipreplace the first impulse might be to save copy of that file and change the find_replace method to scale_image or something similar butthat' uncool what if someday we want to change the unzip and zip methods to also open tar filesor maybe we want to use guaranteed unique directory name for temporary files in either casewe' have to change it in two different placeswe'll start by demonstrating an inheritance-based solution to this problem first we'll modify our original zipreplace class into superclass for processing generic zip filesimport os import shutil import zipfile from pathlib import path class zipprocessordef __init__(selfzipname)self zipname zipname |
3,374 | self temp_directory path("unzipped-{}formatzipname[:- ])def process_zip(self)self unzip_files(self process_files(self zip_files(def unzip_files(self)self temp_directory mkdir(with zipfile zipfile(self zipnameas zipzip extractall(str(self temp_directory)def zip_files(self)with zipfile zipfile(self zipname' 'as filefor filename in self temp_directory iterdir()file write(str(filename)filename nameshutil rmtree(str(self temp_directory)we changed the filename property to zipname to avoid confusion with the filename local variables inside the various methods this helps make the code more readable even though it isn' actually change in design we also dropped the two parameters to __init__ (search_string and replace_ stringthat were specific to zipreplace then we renamed the zip_find_replace method to process_zip and made it call an (as yet undefinedprocess_files method instead of find_replacethese name changes help demonstrate the more generalized nature of our new class notice that we have removed the find_replace method altogetherthat code is specific to zipreplace and has no business here this new zipprocessor class doesn' actually define process_files methodso if we ran it directlyit would raise an exception because it isn' meant to run directlywe removed the main call at the bottom of the original script nowbefore we move on to our image processing applet' fix up our original zipsearch class to make use of this parent classfrom zip_processor import zipprocessor import sys import os class zipreplace(zipprocessor)def __init__(selffilenamesearch_stringreplace_string)super(__init__(filename |
3,375 | self search_string search_string self replace_string replace_string def process_files(self)'''perform search and replace on all files in the temporary directory''for filename in self temp_directory iterdir()with filename open(as filecontents file read(contents contents replaceself search_stringself replace_stringwith filename open(" "as filefile write(contentsif __name__ ="__main__"zipreplace(*sys argv[ : ]process_zip(this code is bit shorter than the original versionsince it inherits its zip processing abilities from the parent class we first import the base class we just wrote and make zipreplace extend that class then we use super(to initialize the parent class the find_replace method is still herebut we renamed it to process_files so the parent class can call it from its management interface because this name isn' as descriptive as the old onewe added docstring to describe what it is doing nowthat was quite bit of workconsidering that all we have now is program that is functionally not different from the one we started withbut having done that workit is now much easier for us to write other classes that operate on files in zip archivesuch as the (hypothetically requestedphoto scaler furtherif we ever want to improve or bug fix the zip functionalitywe can do it for all classes by changing only the one zipprocessor base class maintenance will be much more effective see how simple it is now to create photo scaling class that takes advantage of the zipprocessor functionality (notethis class requires the third-party pillow library to get the pil module you can install it with pip install pillow from zip_processor import zipprocessor import sys from pil import image class scalezip(zipprocessor)def process_files(self)'''scale each image in the directory to ''for filename in self temp_directory iterdir()im image open(str(filename) |
3,376 | scaled im resize(( )scaled save(str(filename)if __name__ ="__main__"scalezip(*sys argv[ : ]process_zip(look how simple this class isall that work we did earlier paid off all we do is open each file (assuming that it is an imageit will unceremoniously crash if file cannot be opened)scale itand save it back the zipprocessor class takes care of the zipping and unzipping without any extra work on our part case study for this case studywe'll try to delve further into the question"when should choose an object versus built-in type?we'll be modeling document class that might be used in text editor or word processor what objectsfunctionsor properties should it havewe might start with str for the document contentsbut in pythonstrings aren' mutable (able to be changedonce str is definedit is forever we can' insert character into it or remove one without creating brand new string object that would be leaving lot of str objects taking up memory until python' garbage collector sees fit to clean up behind us soinstead of stringwe'll use list of characterswhich we can modify at will in additiona document class would need to know the current cursor position within the listand should probably also store filename for the document real text editors use binary-tree based data structure called rope to model their document contents this book' title isn' "advanced data structures"so if you're interested in learning more about this fascinating topicyou may want to search the web for the rope data structure nowwhat methods should it havethere are lot of things we might want to do to text documentincluding insertingdeletingand selecting characterscutcopypastethe selectionand saving or closing the document it looks like there are copious amounts of both data and behaviorso it makes sense to put all this stuff into its own document class pertinent question isshould this class be composed of bunch of basic python objects such as str filenamesint cursor positionsand list of charactersor should some or all of those things be specially defined objects in their own rightwhat about individual lines and charactersdo they need to have classes of their own |
3,377 | we'll answer these questions as we gobut let' start with the simplest possible document class first and see what it can doclass documentdef __init__(self)self characters [self cursor self filename 'def insert(selfcharacter)self characters insert(self cursorcharacterself cursor + def delete(self)del self characters[self cursordef save(self)with open(self filename' 'as ff write('join(self characters)def forward(self)self cursor + def back(self)self cursor - this simple class allows us full control over editing basic document have look at it in actiondoc document(doc filename "test_documentdoc insert(' 'doc insert(' 'doc insert(' 'doc insert(' 'doc insert(' '"join(doc characters'hellodoc back(doc delete(doc insert(' '"join(doc characters'hellp |
3,378 | looks like it' working we could connect keyboard' letter and arrow keys to these methods and the document would track everything just fine but what if we want to connect more than just arrow keys what if we want to connect the home and end keys as wellwe could add more methods to the document class that search forward or backwards for newline characters (in pythona newline characteror \ represents the end of one line and the beginning of new onein the string and jump to thembut if we did that for every possible movement action (move by wordsmove by sentencespage uppage downend of linebeginning of whitespaceand more)the class would be huge maybe it would be better to put those methods on separate object solet us turn the cursor attribute into an object that is aware of its position and can manipulate that position we can move the forward and back methods to that classand add couple more for the home and end keysclass cursordef __init__(selfdocument)self document document self position def forward(self)self position + def back(self)self position - def home(self)while self document charactersself position- !'\ 'self position - if self position = got to beginning of file before newline break def end(self)while self position len(self document characters and self document charactersself position!'\ 'self position + this class takes the document as an initialization parameter so the methods have access to the content of the document' character list it then provides simple methods for moving backwards and forwardsas beforeand for moving to the home and end positions |
3,379 | this code is not very safe you can very easily move past the ending positionand if you try to go home on an empty fileit will crash these examples are kept short to make them readablebut that doesn' mean they are defensiveyou can improve the error checking of this code as an exerciseit might be great opportunity to expand your exception handling skills the document class itself is hardly changedexcept for removing the two methods that were moved to the cursor classclass documentdef __init__(self)self characters [self cursor cursor(selfself filename 'def insert(selfcharacter)self characters insert(self cursor positioncharacterself cursor forward(def delete(self)del self characters[self cursor positiondef save(self) open(self filename' ' write('join(self characters) close(we simply updated anything that accessed the old cursor integer to use the new object instead we can test that the home method is really moving to the newline characterd document( insert(' ' insert(' ' insert(' ' insert(' ' insert(' ' insert('\ ' insert(' ' |
3,380 | insert(' ' insert(' ' insert(' ' insert(' ' cursor home( insert("*"print("join( characters)hello *world nowsince we've been using that string join function lot (to concatenate the characters so we can see the actual document contents)we can add property to the document class to give us the complete string@property def string(self)return "join(self charactersthis makes our testing little simplerprint( stringhello world this framework is simple (though it might be bit time consuming!to extend to create and edit complete plaintext document nowlet' extend it to work for rich texttext that can have boldunderlinedor italic characters there are two ways we could process thisthe first is to insert "fakecharacters into our character list that act like instructionssuch as "bold characters until you find stop bold characterthe second is to add information to each character indicating what formatting it should have while the former method is probably more commonwe'll implement the latter solution to do thatwe're obviously going to need class for characters this class will have an attribute representing the characteras well as three boolean attributes representing whether it is bolditalicor underlined hmmwaitis this character class going to have any methodsif notmaybe we should use one of the many python data structures insteada tuple or named tuple would probably be sufficient are there any actions that we would want to do toor invoke on character |
3,381 | wellclearlywe might want to do things with characterssuch as delete or copy thembut those are things that need to be handled at the document levelsince they are really modifying the list of characters are there things that need to be done to individual charactersactuallynow that we're thinking about what character class actually is what is itwould it be safe to say that character class is stringmaybe we should use an inheritance relationship herethen we can take advantage of the numerous methods that str instances come with what sorts of methods are we talking aboutthere' startswithstripfindlowerand many more most of these methods expect to be working on strings that contain more than one character in contrastif character were to subclass strwe' probably be wise to override __init__ to raise an exception if multi-character string were supplied since all those methods we' get for free wouldn' really apply to our character classit seems we needn' use inheritanceafter all this brings us back to our original questionshould character even be classthere is very important special method on the object class that we can take advantage of to represent our characters this methodcalled __str__ (two underscoreslike __init__)is used in string manipulation functions like print and the str constructor to convert any class to string the default implementation does some boring stuff like printing the name of the module and class and its address in memory but if we override itwe can make it print whatever we like for our implementationwe could make it prefix characters with special characters to represent whether they are bolditalicor underlined sowe will create class to represent characterand here it isclass characterdef __init__(selfcharacterbold=falseitalic=falseunderline=false)assert len(character= self character character self bold bold self italic italic self underline underline def __str__(self)bold "*if self bold else 'italic "/if self italic else 'underline "_if self underline else 'return bold italic underline self character |
3,382 | this class allows us to create characters and prefix them with special character when the str(function is applied to them nothing too exciting there we only have to make few minor modifications to the document and cursor classes to work with this class in the document classwe add these two lines at the beginning of the insert methoddef insert(selfcharacter)if not hasattr(character'character')character character(characterthis is rather strange bit of code its basic purpose is to check whether the character being passed in is character or str if it is stringit is wrapped in character class so all objects in the list are character objects howeverit is entirely possible that someone using our code would want to use class that is neither character nor stringusing duck typing if the object has character attributewe assume it is "character-likeobject but if it does notwe assume it is "str-likeobject and wrap it in character this helps the program take advantage of duck typing as well as polymorphismas long as an object has character attributeit can be used in the document class this generic check could be very usefulfor exampleif we wanted to make programmer' editor with syntax highlightingwe' need extra data on the charactersuch as what type of syntax token the character belongs to note that if we are doing lot of this kind of comparisonit' probably better to implement character as an abstract base class with an appropriate __subclasshook__as discussed in when objects are alike in additionwe need to modify the string property on document to accept the new character values all we need to do is call str(on each character before we join it@property def string(self)return "join((str(cfor in self characters)this code uses generator expressionwhich we'll discuss in the iterator pattern it' shortcut to perform specific action on all the objects in sequence finallywe also need to check character characterinstead of just the string character we were storing beforein the home and end functions when we're looking to see whether it matches newline characterdef home(self)while self document charactersself position- character !'\ 'self position - if self position = |
3,383 | got to beginning of file before newline break def end(self)while self position lenself document charactersand self document charactersself position character !'\ 'self position + this completes the formatting of characters we can test it to see that it worksd document( insert(' ' insert(' ' insert(character(' 'bold=true) insert(character(' 'bold=true) insert(' ' insert('\ ' insert(character(' 'italic=true) insert(character(' 'italic=true) insert(character(' 'underline=true) insert(' ' insert(' 'print( stringhe* *lo / /o_rld cursor home( delete( insert(' 'print( stringhe* *lo /o_rld characters[ underline true print( string_he* *lo /o_rld |
3,384 | as expectedwhenever we print the stringeach bold character is preceded by charactereach italic character by characterand each underlined character by character all our functions seem to workand we can modify characters in the list after the fact we have working rich text document object that could be plugged into proper user interface and hooked up with keyboard for input and screen for output naturallywe' want to display real bolditalicand underlined characters on the screeninstead of using our __str__ methodbut it was sufficient for the basic testing we demanded of it exercises we've looked at various ways that objectsdataand methods can interact with each other in an object-oriented python program as usualyour first thoughts should be how you can apply these principles to your own work do you have any messy scripts lying around that could be rewritten using an object-oriented managerlook through some of your old code and look for methods that are not actions if the name isn' verbtry rewriting it as property think about code you've written in any language does it break the dry principleis there any duplicate codedid you copy and paste codedid you write two versions of similar pieces of code because you didn' feel like understanding the original codego back over some of your recent code now and see whether you can refactor the duplicate code using inheritance or composition try to pick project you're still interested in maintainingnot code so old that you never want to touch it again it helps keep your interest up when you do the improvementsnowlook back over some of the examples we saw in this start with the cached web page example that uses property to cache the retrieved data an obvious problem with this example is that the cache is never refreshed add timeout to the property' getterand only return the cached page if the page has been requested before the timeout has expired you can use the time module (time time(an_old_time returns the number of seconds that have elapsed since an_old_timeto determine whether the cache has expired now look at the inheritance-based zipprocessor it might be reasonable to use composition instead of inheritance here instead of extending the class in the zipreplace and scalezip classesyou could pass instances of those classes into the zipprocessor constructor and call them to do the processing part implement this |
3,385 | which version do you find easier to usewhich is more elegantwhat is easier to readthese are subjective questionsthe answer varies for each of us knowing the answerhoweveris importantif you find you prefer inheritance over compositionyou have to pay attention that you don' overuse inheritance in your daily coding if you prefer compositionmake sure you don' miss opportunities to create an elegant inheritance-based solution finallyadd some error handlers to the various classes we created in the case study they should ensure single characters are enteredthat you don' try to move the cursor past the end or beginning of the filethat you don' delete character that doesn' existand that you don' save file without filename try to think of as many edge cases as you canand account for them (thinking about edge cases is about percent of professional programmer' job!consider different ways to handle themshould you raise an exception when the user tries to move past the end of the fileor just stay on the last characterpay attentionin your daily codingto the copy and paste commands every time you use them in your editorconsider whether it would be good idea to improve your program' organization so that you only have one version of the code you are about to copy summary in this we focused on identifying objectsespecially objects that are not immediately apparentobjects that manage and control objects should have both data and behaviorbut properties can be used to blur the distinction between the two the dry principle is an important indicator of code quality and inheritance and composition can be applied to reduce code duplication in the next we'll cover several of the built-in python data structures and objectsfocusing on their object-oriented properties and how they can be extended or adapted |
3,386 | in our examples so farwe've already seen many of the built-in python data structures in action you've probably also covered many of them in introductory books or tutorials in this we'll be discussing the object-oriented features of these data structureswhen they should be used instead of regular classand when they should not be used in particularwe'll be coveringtuples and named tuples dictionaries lists and sets how and why to extend built-in objects three types of queues empty objects let' start with the most basic python built-inone that we've seen many times alreadythe one that we've extended in every class we have createdthe object technicallywe can instantiate an object without writing subclasso object( traceback (most recent call last)file ""line in attributeerror'objectobject has no attribute ' |
3,387 | unfortunatelyas you can seeit' not possible to set any attributes on an object that was instantiated directly this isn' because the python developers wanted to force us to write our own classesor anything so sinister they did this to save memorya lot of memory when python allows an object to have arbitrary attributesit takes certain amount of system memory to keep track of what attributes each object hasfor storing both the attribute name and its value even if no attributes are storedmemory is allocated for potential new attributes given the dozenshundredsor thousands of objects (every class extends objectin typical python programthis small amount of memory would quickly become large amount of memory sopython disables arbitrary properties on objectand several other built-insby default it is possible to restrict arbitrary properties on our own classes using slots slots are beyond the scope of this bookbut you now have search term if you are looking for more information in normal usethere isn' much benefit to using slotsbut if you're writing an object that will be duplicated thousands of times throughout the systemthey can help save memoryjust as they do for object it ishowevertrivial to create an empty object class of our ownwe saw it in our earliest exampleclass myobjectpass andas we've already seenit' possible to set attributes on such classesm myobject( "hellom 'helloif we wanted to group properties togetherwe could store them in an empty object like this but we are usually better off using other built-ins designed for storing data it has been stressed throughout this book that classes and objects should only be used when you want to specify both data and behaviors the main reason to write an empty class is to quickly block something outknowing we'll come back later to add behavior it is much easier to adapt behaviors to class than it is to replace data structure with an object and change all references to it thereforeit is important to decide from the outset if the data is just dataor if it is an object in disguise once that design decision is madethe rest of the design naturally falls into place |
3,388 | tuples and named tuples tuples are objects that can store specific number of other objects in order they are immutableso we can' addremoveor replace objects on the fly this may seem like massive restrictionbut the truth isif you need to modify tupleyou're using the wrong data type (usually list would be more suitablethe primary benefit of tuplesimmutability is that we can use them as keys in dictionariesand in other locations where an object requires hash value tuples are used to store databehavior cannot be stored in tuple if we require behavior to manipulate tuplewe have to pass the tuple into function (or method on another objectthat performs the action tuples should generally store values that are somehow different from each other for examplewe would not put three stock symbols in tuplebut we might create tuple of stock symbolcurrent pricehighand low for the day the primary purpose of tuple is to aggregate different pieces of data together into one container thusa tuple can be the easiest tool to replace the "object with no dataidiom we can create tuple by separating the values with comma usuallytuples are wrapped in parentheses to make them easy to read and to separate them from other parts of an expressionbut this is not always mandatory the following two assignments are identical (they record stockthe current pricethe highand the low for rather profitable company)stock "fb" stock ("fb" if we're grouping tuple inside of some other objectsuch as function calllist comprehensionor generatorthe parentheses are required otherwiseit would be impossible for the interpreter to know whether it is tuple or the next function parameter for examplethe following function accepts tuple and dateand returns tuple of the date and the middle value between the stock' high and low valueimport datetime def middle(stockdate)symbolcurrenthighlow stock return (((high low )datemid_valuedate middle(("fb" )datetime date( )the tuple is created directly inside the function call by separating the values with commas and enclosing the entire tuple in parenthesis this tuple is then followed by comma to separate it from the second argument |
3,389 | this example also illustrates tuple unpacking the first line inside the function unpacks the stock parameter into four different variables the tuple has to be exactly the same length as the number of variablesor it will raise an exception we can also see an example of tuple unpacking on the last linewhere the tuple returned inside the function is unpacked into two valuesmid_value and date grantedthis is strange thing to dosince we supplied the date to the function in the first placebut it gave us chance to see unpacking at work unpacking is very useful feature in python we can group variables together to make storing and passing them around simplerbut the moment we need to access all of themwe can unpack them into separate variables of coursesometimes we only need access to one of the variables in the tuple we can use the same syntax that we use for other sequence types (lists and stringsfor exampleto access an individual valuestock "fb" high stock[ high we can even use slice notation to extract larger pieces of tuplesstock[ : ( these exampleswhile illustrating how flexible tuples can bealso demonstrate one of their major disadvantagesreadability how does someone reading this code know what is in the second position of specific tuplethey can guessfrom the name of the variable we assigned it tothat it is high of some sortbut if we had just accessed the tuple value in calculation without assigning itthere would be no such indication they would have to paw through the code to find where the tuple was declared before they could discover what it does accessing tuple members directly is fine in some circumstancesbut don' make habit of it such so-called "magic numbers(numbers that seem to come out of thin air with no apparent meaning within the codeare the source of many coding errors and lead to hours of frustrated debugging try to use tuples only when you know that all the values are going to be useful at once and it' normally going to be unpacked when it is accessed if you have to access member directly or using slice and the purpose of that value is not immediately obviousat least include comment explaining where it came from |
3,390 | named tuples sowhat do we do when we want to group values togetherbut know we're frequently going to need to access them individuallywellwe could use an empty objectas discussed in the previous section (but that is rarely useful unless we anticipate adding behavior later)or we could use dictionary (most useful if we don' know exactly how many or which specific data will be stored)as we'll cover in the next section ifhoweverwe do not need to add behavior to the objectand we know in advance what attributes we need to storewe can use named tuple named tuples are tuples with attitude they are great way to group read-only data together constructing named tuple takes bit more work than normal tuple firstwe have to import namedtupleas it is not in the namespace by default thenwe describe the named tuple by giving it name and outlining its attributes this returns class-like object that we can instantiate with the required values as many times as we wantfrom collections import namedtuple stock namedtuple("stock""symbol current high low"stock stock("fb" high= low= the namedtuple constructor accepts two arguments the first is an identifier for the named tuple the second is string of space-separated attributes that the named tuple can have the first attribute should be listedfollowed by space (or comma if you prefer)then the second attributethen another spaceand so on the result is an object that can be called just like normal class to instantiate other objects the constructor must have exactly the right number of arguments that can be passed in as arguments or keyword arguments as with normal objectswe can create as many instances of this "classas we likewith different values for each the resulting namedtuple can then be packedunpackedand otherwise treated like normal tuplebut we can also access individual attributes on it as if it were an objectstock high symbolcurrenthighlow stock current remember that creating named tuples is two-step process firstuse collections namedtuple to create classand then construct instances of that class |
3,391 | named tuples are perfect for many "data onlyrepresentationsbut they are not ideal for all situations like tuples and stringsnamed tuples are immutableso we cannot modify an attribute once it has been set for examplethe current value of my company' stock has gone down since we started this discussionbut we can' set the new valuestock current traceback (most recent call last)file ""line in attributeerrorcan' set attribute if we need to be able to change stored dataa dictionary may be what we need instead dictionaries dictionaries are incredibly useful containers that allow us to map objects directly to other objects an empty object with attributes to it is sort of dictionarythe names of the properties map to the property values this is actually closer to the truth than it soundsinternallyobjects normally represent attributes as dictionarywhere the values are properties or methods on the objects (see the __dict__ attribute if you don' believe meeven the attributes on module are storedinternallyin dictionary dictionaries are extremely efficient at looking up valuegiven specific key object that maps to that value they should always be used when you want to find one object based on some other object the object that is being stored is called the valuethe object that is being used as an index is called the key we've already seen dictionary syntax in some of our previous examples dictionaries can be created either using the dict(constructor or using the {syntax shortcut in practicethe latter format is almost always used we can prepopulate dictionary by separating the keys from the values using colonand separating the key value pairs using comma for examplein stock applicationwe would most often want to look up prices by the stock symbol we can create dictionary that uses stock symbols as keysand tuples of currenthighand low as values like thisstocks {"goog"( )"msft"( ) |
3,392 | as we've seen in previous exampleswe can then look up values in the dictionary by requesting key inside square brackets if the key is not in the dictionaryit will raise an exceptionstocks["goog"( stocks["rim"traceback (most recent call last)file ""line in keyerror'rimwe canof coursecatch the keyerror and handle it but we have other options rememberdictionaries are objectseven if their primary purpose is to hold other objects as suchthey have several behaviors associated with them one of the most useful of these methods is the get methodit accepts key as the first parameter and an optional default value if the key doesn' existprint(stocks get("rim")none stocks get("rim""not found"'not foundfor even more controlwe can use the setdefault method if the key is in the dictionarythis method behaves just like getit returns the value for that key otherwiseif the key is not in the dictionaryit will not only return the default value we supply in the method call (just like get does)it will also set the key to that same value another way to think of it is that setdefault sets value in the dictionary only if that value has not previously been set then it returns the value in the dictionaryeither the one that was already thereor the newly provided default value stocks setdefault("goog""invalid"( stocks setdefault("bbry"( )( stocks["bbry"( |
3,393 | the goog stock was already in the dictionaryso when we tried to setdefault it to an invalid valueit just returned the value already in the dictionary bbry was not in the dictionaryso setdefault returned the default value and set the new value in the dictionary for us we then check that the new stock isindeedin the dictionary three other very useful dictionary methods are keys()values()and items(the first two return an iterator over all the keys and all the values in the dictionary we can use these like lists or in for loops if we want to process all the keys or values the items(method is probably the most usefulit returns an iterator over tuples of (keyvaluepairs for every item in the dictionary this works great with tuple unpacking in for loop to loop over associated keys and values this example does just that to print each stock in the dictionary with its current valuefor stockvalues in stocks items()print("{last value is {}format(stockvalues[ ])goog last value is bbry last value is msft last value is each key/value tuple is unpacked into two variables named stock and values (we could use any variable names we wantedbut these both seem appropriateand then printed in formatted string notice that the stocks do not show up in the same order in which they were inserted dictionariesdue to the efficient algorithm (known as hashingthat is used to make key lookup so fastare inherently unsorted sothere are numerous ways to retrieve data from dictionary once it has been instantiatedwe can use square brackets as index syntaxthe get methodthe setdefault methodor iterate over the items methodamong others finallyas you likely already knowwe can set value in dictionary using the same indexing syntax we use to retrieve valuestocks["goog"( stocks['goog'( google' price is lower todayso 've updated the tuple value in the dictionary we can use this index syntax to set value for any keyregardless of whether the key is in the dictionary if it is in the dictionarythe old value will be replaced with the new oneotherwisea new key/value pair will be created |
3,394 | we've been using strings as dictionary keysso farbut we aren' limited to string keys it is common to use strings as keysespecially when we're storing data in dictionary to gather it together (instead of using an object with named propertiesbut we can also use tuplesnumbersor even objects we've defined ourselves as dictionary keys we can even use different types of keys in single dictionaryrandom_keys {random_keys["astring""somestringrandom_keys[ "anintegerrandom_keys[ "floats work toorandom_keys[("abc" )"so do tuplesclass anobjectdef __init__(selfavalue)self avalue avalue my_object anobject( random_keys[my_object"we can even store objectsmy_object avalue tryrandom_keys[[ , , ]"we can' store lists thoughexceptprint("unable to store list\ "for keyvalue in random_keys items()print("{has value {}format(keyvalue)this code shows several different types of keys we can supply to dictionary it also shows one type of object that cannot be used we've already used lists extensivelyand we'll be seeing many more details of them in the next section because lists can change at any time (by adding or removing itemsfor example)they cannot hash to specific value objects that are hashable basically have defined algorithm that converts the object into unique integer value for rapid lookup this hash is what is actually used to look up values in dictionary for examplestrings map to integers based on the characters in the stringwhile tuples combine hashes of the items inside the tuple any two objects that are somehow considered equal (like strings with the same characters or tuples with the same valuesshould have the same hash valueand the hash value for an object should never ever change listshowevercan have their contents changedwhich would change their hash value (two lists should only be equal if their contents are the samebecause of thisthey can' be used as dictionary keys for the same reasondictionaries cannot be used as keys into other dictionaries |
3,395 | in contrastthere are no limits on the types of objects that can be used as dictionary values we can use string key that maps to list valuefor exampleor we can have nested dictionary as value in another dictionary dictionary use cases dictionaries are extremely versatile and have numerous uses there are two major ways that dictionaries can be used the first is dictionaries where all the keys represent different instances of similar objectsfor exampleour stock dictionary this is an indexing system we use the stock symbol as an index to the values the values could even have been complicated self-defined objects that made buy and sell decisions or set stop-lossrather than our simple tuples the second design is dictionaries where each key represents some aspect of single structurein this casewe' probably use separate dictionary for each objectand they' all have similar (though often not identicalsets of keys this latter situation can often also be solved with named tuples these should typically be used when we know exactly what attributes the data must storeand we know that all pieces of the data must be supplied at once (when the item is constructedbut if we need to create or change dictionary keys over time or we don' know exactly what the keys might bea dictionary is more suitable using defaultdict we've seen how to use setdefault to set default value if key doesn' existbut this can get bit monotonous if we need to set default value every time we look up value for exampleif we're writing code that counts the number of times letter occurs in given sentencewe could do thisdef letter_frequency(sentence)frequencies {for letter in sentencefrequency frequencies setdefault(letter frequencies[letterfrequency return frequencies every time we access the dictionarywe need to check that it has value alreadyand if notset it to zero when something like this needs to be done every time an empty key is requestedwe can use different version of the dictionarycalled defaultdictfrom collections import defaultdict def letter_frequency(sentence)frequencies defaultdict(int |
3,396 | for letter in sentencefrequencies[letter+ return frequencies this code looks like it couldn' possibly work the defaultdict accepts function in its constructor whenever key is accessed that is not already in the dictionaryit calls that functionwith no parametersto create default value in this casethe function it calls is intwhich is the constructor for an integer object normallyintegers are created simply by typing an integer number into our codeand if we do create one using the int constructorwe pass it the item we want to create (for exampleto convert string of digits into an integerbut if we call int without any argumentsit returnsconvenientlythe number zero in this codeif the letter doesn' exist in the defaultdictthe number zero is returned when we access it then we add one to this number to indicate we've found an instance of that letterand the next time we find onethat number will be returned and we can increment the value again the defaultdict is useful for creating dictionaries of containers if we want to create dictionary of stock prices for the past dayswe could use stock symbol as the key and store the prices in listthe first time we access the stock pricewe would want it to create an empty list simply pass list into the defaultdictand it will be called every time an empty key is accessed we can do similar things with sets or even empty dictionaries if we want to associate one with key of coursewe can also write our own functions and pass them into the defaultdict suppose we want to create defaultdict where each new element contains tuple of the number of items inserted into the dictionary at that time and an empty list to hold other things nobody knows why we would want to create such an objectbut let' have lookfrom collections import defaultdict num_items def tuple_counter()global num_items num_items + return (num_items[] defaultdict(tuple_counterwhen we run this codewe can access empty keys and insert into the list all in one statementd defaultdict(tuple_counterd[' '][ append("hello" [' '][ append('world' |
3,397 | defaultdict({' '( ['hello'])' '( ['world'])}when we print dict at the endwe see that the counter really was working this examplewhile succinctly demonstrating how to create our own function for defaultdictis not actually very good codeusing global variable means that if we created four different defaultdict segments that each used tuple_counterit would count the number of entries in all dictionariesrather than having different count for each one it would be better to create class and pass method on that class to defaultdict counter you' think that you couldn' get much simpler than defaultdict(int)but the " want to count specific instances in an iterableuse case is common enough that the python developers created specific class for it the previous code that counts characters in string can easily be calculated in single linefrom collections import counter def letter_frequency(sentence)return counter(sentencethe counter object behaves like beefed up dictionary where the keys are the items being counted and the values are the number of such items one of the most useful functions is the most_common(method it returns list of (keycounttuples ordered by the count you can optionally pass an integer argument into most_common(to request only the top most common elements for exampleyou could write simple polling application as followsfrom collections import counter responses "vanilla""chocolate""vanilla""vanilla""caramel""strawberry""vanillaprint |
3,398 | "the children voted for {ice creamformatcounter(responsesmost_common( )[ ][ presumablyyou' get the responses from database or by using complicated vision algorithm to count the kids who raised their hands herewe hardcode it so that we can test the most_common method it returns list that has only one element (because we requested one element in the parameterthis element stores the name of the top choice at position zerohence the double [ ][ at the end of the call think they look like surprised facedon' youyour computer is probably amazed it can count data so easily it' ancestorhollerith' tabulating machine for the us censusmust be so jealouslists lists are the least object-oriented of python' data structures while lists arethemselvesobjectsthere is lot of syntax in python to make using them as painless as possible unlike many other object-oriented languageslists in python are simply available we don' need to import them and rarely need to call methods on them we can loop over list without explicitly requesting an iterator objectand we can construct list (as with dictionarywith custom syntax furtherlist comprehensions and generator expressions turn them into veritable swiss-army knife of computing functionality we won' go into too much detail of the syntaxyou've seen it in introductory tutorials across the web and in previous examples in this book you can' code python very long without learning how to use listsinsteadwe'll be covering when lists should be usedand their nature as objects if you don' know how to create or append to listhow to retrieve items from listor what "slice notationisi direct you to the official python tutorialpost-haste it can be found online at tutorialin pythonlists should normally be used when we want to store several instances of the "sametype of objectlists of strings or lists of numbersmost oftenlists of objects we've defined ourselves lists should always be used when we want to store items in some kind of order oftenthis is the order in which they were insertedbut they can also be sorted by some criteria as we saw in the case study from the previous lists are also very useful when we need to modify the contentsinsert to or delete from an arbitrary location of the listor update value within the list |
3,399 | like dictionariespython lists use an extremely efficient and well-tuned internal data structure so we can worry about what we're storingrather than how we're storing it many object-oriented languages provide different data structures for queuesstackslinked listsand array-based lists python does provide special instances of some of these classesif optimizing access to huge sets of data is required normallyhoweverthe list data structure can serve all these purposes at onceand the coder has complete control over how they access it don' use lists for collecting different attributes of individual items we do not wantfor examplea list of the properties particular shape has tuplesnamed tuplesdictionariesand objects would all be more suitable for this purpose in some languagesthey might create list in which each alternate item is different typefor examplethey might write [' ' ' ' for our letter frequency list they' have to use strange loop that accesses two elements in the list at once or modulus operator to determine which position was being accessed don' do this in python we can group related items together using dictionaryas we did in the previous section (if sort order doesn' matter)or using list of tuples here' rather convoluted example that demonstrates how we could do the frequency example using list it is much more complicated than the dictionary examplesand illustrates the effect choosing the right (or wrongdata structure can have on the readability of our codeimport string characters list(string ascii_letters["def letter_frequency(sentence)frequencies [( for in charactersfor letter in sentenceindex characters index(letterfrequencies[index(letter,frequencies[index][ ]+ return frequencies this code starts with list of possible characters the string ascii_letters attribute provides string of all the letterslowercase and uppercasein order we convert this to listand then use list concatenation (the plus operator causes two lists to be merged into oneto add one more characterthe space these are the available characters in our frequency list (the code would break if we tried to add letter that wasn' in the listbut an exception handler could solve this |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.