id
int64
0
25.6k
text
stringlengths
0
4.59k
7,900
def register(selfuserobj)if userobj not in self _listofusersself _listofusers append(userobjdef unregister(selfuserobj)self _listofusers remove(userobjdef notifyall(self)for objects in self _listofusersobjects notify(self postnamedef writenewpost(selfpostname)user writes post self postname postname when submits the pos...
7,901
sites sistersites(techforum register(user techforum register(user techforum register(sitestechforum writenewpost("observer pattern in python"techforum unregister(user techforum writenewpost("mvc pattern in python" www testingperspective com
7,902
dp facade pattern introduction facade( )the face or front of building as per wikipedia"the facade pattern is software engineering design pattern commonly used with object-oriented programming (the name is by analogy to an architectural facade facade is an object that provides simplified interface to larger body of code...
7,903
the pattern can be better explained with block diagram (based on facade pattern example from wikipedia in this block diagramwe have three classes representing the cputhe memory and the harddrive of computer cpu class has methods called as jump(and execute(memory class has method load(and harddrive class has read(method...
7,904
as discussed earlierin this implementationonly thing achieved via facade is --starting|the computer there could be other finer operations in cpu/memory/harddrive classeswhich could be achieved by the client only by directly calling their methods sample python implementation example description let' consider the case of...
7,905
print "running testtime sleep( print "tearing downtime sleep( print "test finished\nclass tc def run(self)print "#####in test ######time sleep( print "setting uptime sleep( print "running testtime sleep( print "tearing downtime sleep( print "test finished\ #facade class testrunnerdef __init__(self)self tc tc (self tc t...
7,906
dp mediator pattern introduction as per wikipediathe mediator pattern provides unified interface to set of interfaces in subsystem this pattern is considered to be behavioral pattern due to the way it can alter the program' running behavior typicallymediator pattern is used in cases where many classes start communicati...
7,907
sample python implementation example description typical example of mediator pattern can be manifested in test automation framework which consists of four classes namelytc (testcategory)testmanagerreporter and db(database class tc is responsible for running the tests with the help of setup()execute(and teardown(methods...
7,908
time sleep( self _tm preparereporting(def execute(self)if not self _bproblemprint "executing the testtime sleep( elseprint "problem in setup test not executed def teardown(self)if not self _bproblemprint "tearing downtime sleep( self _tm publishreport(elseprint "test not executed no tear down required def settm(self,tm...
7,909
#following code is to simulate communication from db to tc import random if random randrange( , = return - def update(self)print "updating the test results in databasetime sleep( def settm(self,tm)self _tm tm class testmanagerdef __init__(self)self _reporter none self _db none self _tc none def preparereporting(self)rv...
7,910
for simplification we are looping on the same test practicallyit could be about various unique test classes and their objects while ( )tc tc(tc settm(tmtm settc(tctc setup(tc execute(tc teardown(in the above python codethe user of the framework first creates instances of class reporterclass db and class testmanager and...
7,911
dp factory pattern introduction as per wikipedia"the factory pattern is creational design pattern used in software development to encapsulate the processes involved in the creation of objects factory pattern involves creating super class which provides an abstract interface to create objects of particular typebut inste...
7,912
sample python implementation example description let us consider an example to demonstrate the usage of factory pattern (based on example of factory pattern in java from allapplabs com we have base class called person that has methods for getting the name and the gender and has two sub-classes namely male and female th...
7,913
if __name__ ='__main__'factory factory(person factory getperson("chetan"" " www testingperspective com
7,914
dp proxy pattern introduction as per wikipedia" proxyin its most general formis class functioning as an interface to something else the proxy could interface to anythinga network connectiona large object in memorya fileor some other resource that is expensive or impossible to duplicate well-known example of the proxy p...
7,915
need arises that an object must be protected from direct use by its clients there is need that an object creation for the real subject class can be delayed to point when it is actually required some of the real world examples as described by allapplabs and userpages of proxy pattern arewebsite where the cache proxy can...
7,916
exercises proxy pattern memoization the proxy pattern remote proxy virtual proxy protection proxy parting shots exercises chain of responsibility pattern setting up wsgi server authentication headers the chain of responsibility pattern implementing chain of responsibility in our project more pythonic implementation p...
7,917
parting shots exercises iterator pattern python internal implementation of the iterator pattern itertools generator functions generator expression parting shots exercises observer pattern parting shots exercises state pattern state pattern parting shots exercises strategy pattern parting shots exercises template m...
7,918
model-view-controller skeleton controllers models views bringing it all together parting shots exercises publish-subscribe pattern distributed message sender parting shots exercises appendix adesign pattern quick reference quick checks for the code singleton prototype factory builder adapter decorator facade ...
7,919
state strategy template method visitor model-view-controller publisher-subscriber final words index
7,920
before we begin design patterns help you learn from otherssuccesses instead of your own failures --mark johnson the world is changing as you are reading thispeople all over the world are learning to programmostly poorly there is flood of "programmersheading for the marketand there is nothing you can do to stop them as ...
7,921
before we begin suddenlybeing able create website becomes lot less valuable all the businesses that were consultingcharging big bucks for the serviceget marginalized howeverthe people who spent time mastering the tools are able to thrive no matter what happens in the market they can do this because they are able to out...
7,922
before we begin am still learningstill digging you can do it too start with this very book you are reading right now in it you will find number of tools and mental models to help you think and code better after you have mastered this set of patternsactively seek out and master different tools and techniques play with d...
7,923
before we begin focus on deliberate practice practice systems thinking whenever you can find an excuse collect and analyze mental models master your tools and understand what they are good for and what they should not be used for deliberate practice dr anders erickson studied people who reached level of performance we...
7,924
before we begin in programmingyou want to learn different ways to solve problems you want to find different challenges that force you to attack the same type of problem with different constraints keep working at it until you understand the problem and the set of possible solutions inside out in essencedeliberate practi...
7,925
before we begin too long to really be able to see the effects of experiments with programming this is not the caseyou can write piece of code and then run it for instant feedback this allows you to course correct and ultimately reach an acceptable solution if you go one step further and write solid tests for your codey...
7,926
before we begin sowhat should you work on firstthat thing you thought of as you read the previous two paragraphs working your way through the design patterns in this book is another good way of finding potential growth areas just start with the singleton pattern and work your way through stand on the shoulders of gian...
7,927
before we begin once you are comfortable with the solution as you found ittry to improve on the original solution you need to learn to think about the solutions you find out there-what makes them goodhow can you make them more elegantmore idiomaticmore simplealways look for opportunities to make code better in one of t...
7,928
before we begin this self-awareness gives you the ability to know when to try one more thing and when to head in different direction systems thinking everything is system by understanding what elements make up the systemhow they are connectedand how they interact with one anotheryou can understand the system by learni...
7,929
before we begin the better--and by better mean more complete--the problem definition or description isthe more hints you have of what possible solution would look like soask yourself dumb questions about the problem until you have clear and simple problem statement design patterns help you go from (the problem statemen...
7,930
before we begin design patterns as concept the gang of four' book on design patterns seems to be the place where it all started they set forth framework for describing design patterns (specifically for ++)but the description was focused on the solution in generaland as result many of the patterns were translated into ...
7,931
before we begin collaborations consequences/constraints implementation sample code known uses related patterns in appendix ayou can find all the design patterns we discuss in this book structured according to these elements for the sake of readability and the learning processthe on the design patterns themselves will n...
7,932
before we begin behavioral these design patterns are focused on the interaction between objects the tools we will be using the world is shifting toward python this shift is slow and deliberate andlike glaciercannot be stopped for the sake of this bookwe will release python and embrace the future that saidyou should b...
7,933
before we begin the second group wants to be able to find specific solutions to specific problems for those readerseach design pattern starts with description of the problem addressed by the pattern in question this should help you decide if the pattern will be helpful in solving the problem you are faced with the last...
7,934
before we begin this will install python you can check the version of the python installas beforeto verify that the right version was installedpython --version python should now be available on your system nextwe install build essentials and python pipsudo apt-get install python-pip build-essential nowcheck that pip is...
7,935
before we begin to run brew commands from any folder in the terminalyou need to add the homebrew path to your path environment variable open or create ~bash_profile and add the following line at the end of the fileexport path=/usr/local/bin:$path close and reopen terminal upon reopeningthe new path variable will be inc...
7,936
before we begin with the installyou also get idlewhich is an interactive python shell this lets you run python commands in real-time interpreterwhich is great for testing ideas or playing around with new packages once you are done with the installopen your command-line interfacewindowsbutton- cmd this will open termina...
7,937
before we begin now that you have the virtualenv packagelet' use it to create an environment to use with this book in your terminalgo to the directory you will be working in nextcreate virtual environment where you will install the packages needed for the projects in this book our virtual environment will be called ppd...
7,938
before we begin what follows is short list of my favorite text editorswith couple of notes on each tom github made an editorthey called it atomand it is simplebeautifuland functional editor right out of the box it offers simple git integration and good package system (including real-time markdown compilerthe fact that ...
7,939
before we begin the yearsvim accumulated number of extensionscolor themesand every feature full-fledged ide would dream of it has its own package manager and gives you total control over every aspect of code editing it is free and is the quickest out of the blocks of any editor have seen for all its prosvim is hard to ...
7,940
before we begin summary in the endit does not matter which editor you choose to use it must be something you feel comfortable with whatever you choosetake the time to master this tool if you want to be productiveyou must master any tool or process you have to use every dayno matter how mundane it may seem what suggest...
7,941
the singleton pattern there can be only one!--connor macleod the problem one of the first debugging techniques you learn is simply printing the values of certain variables to the console this helps you see what is going on inside your program when the programs you write become more complexyou reach point where you cann...
7,942
the singleton pattern now you can see what is happening in the program when things go wrong your log file is like black box on an aircraftit keeps tally of your program' execution when your program crashesyou can pop open the black box and see what happened leading up to the crashas well as where you should start looki...
7,943
the singleton pattern let' create new file called logger py and write the following code in the filelogger py def log_message(msg)with open("/var/log/filename log"" "as log_filelog_file write("{ }\nformat(msg)nowwe can use our new logger function to write log messages to the file system in our main_script py filemain_s...
7,944
the singleton pattern in the log filewe want each message to be prepended with the level associated with the message this helps us easily scan the file for specific types of messages you can use this convention with certain command-line toolslike using grep in nix environment to show only messages of certain level afte...
7,945
the singleton pattern if you look at the output of the _test_error_log py__ functionyou will see that the message now has the level added to the line as prefix[errorsomething went wrong our logging project now has some really useful functionalitybut bet there is something bothering you about the way the logger py file ...
7,946
the singleton pattern this looks even better it is simple and cleanas each function does only one thing the write_log function just writes the message level and message text to the file each log writer simply calls the write_log functionadding the level of the message to the call ' sure you are really beginning to like...
7,947
the singleton pattern enter the objects classes in python allow you to define logical groupings of data and functions they also allow you to add some contextual data to the logger (like which file you want to write toto get the most out of classesyou need to think in slightly new way this grouping of functions and dat...
7,948
the singleton pattern def error(selflevelmsg)self _write_log("error"msgdef warn(selflevelmsg)self _write_log("warn"msgdef info(selflevelmsg)self _write_log("info"msgdef debug(selflevelmsg)self _write_log("debug"msgthere is quite lot happening hereso just look at the code for minute before show you how this new logger i...
7,949
the singleton pattern just quick note with regards to the terms attributes and methods attributes are the pieces of data associated with an object as defined in the class blueprint the functions that perform actions on these pieces of data are referred to as methods when we use the self keyword together with methodlike...
7,950
the singleton pattern we can now import specific class from python file by telling the interpreter which file we want to useand then what class it should import importing from different packages can get more complex than thisbut for now just realizing that you can import the specific class you want to use is enough pac...
7,951
the singleton pattern def __new__(cls)if not singletonobject instancesingletonobject instance singletonobject __singletonobject(return singletonobject instance def __getattr__(selfname)return getattr(self instancenamedef __setattr__(selfname)return setattr(self instancenamedon' panic at firstit seems like lot is happen...
7,952
the singleton pattern in the __new__ functionwe see that whenever programmer tries to instantiate an object of type singletonobjectthe interpreter will first check the class variable instance to see if there is such an instance in existence if there is no existing instanceit creates new instance of the private class an...
7,953
the singleton pattern the main criticism of the singleton pattern is that it is just pretty way to get global statewhich is one of the things you want to avoid when writing programs one of the reasons why you want to avoid global state is that code in one part of your project may alter the global state and cause unexpe...
7,954
the prototype pattern reality doesn' care if you believe in it --boba fettstarwars extended universe the problem can still remember the very first time wanted to program anything this was at time when dos could not address more than mb at timeand thus our massive mb hard drive had to be partitioned into two drives it w...
7,955
the prototype pattern guess lot of people first become interested in programming in some derivative of interest in games and the desire to program games sadlygames tend to be vast and complex systemsand making game that will be fun and popular is massive undertaking without any guarantees of success in the endrelativel...
7,956
the prototype pattern speedattack_powerattack_rangeweapon )self life life self speed speed self attack_power attack_power self attack_range attack_range self weapon weapon def __str__(self)return "life{ }\ "speed{ }\ "attack power{ }\ "attack range{ }\ "weapon{ }formatself lifeself speedself attack_powerself attack_ran...
7,957
the prototype pattern [knight life speed attack power attack range weaponshort sword even though we do not have any draw logic or interaction codeit is quite easy to generate new knight with some default values for the rest of this we will be concerning ourselves with this generation code and will see what it teaches u...
7,958
the prototype pattern attack_powerattack_rangeweapon )self unit_type "knightself life life self speed speed self attack_power attack_power self attack_range attack_range self weapon weapon def __str__(self)return "type{ }\ "life{ }\ "speed{ }\ "attack power{ }\ "attack range{ }\ "weapon{ }formatself unit_typeself lifes...
7,959
the prototype pattern self unit_type "archerself life life self speed speed self attack_power attack_power self attack_range attack_range self weapon weapon def __str__(self)return "type{ }\ "life{ }\ "speed{ }\ "attack power{ }\ "attack range{ }\ "weapon{ }formatself unit_typeself lifeself speedself attack_powerself a...
7,960
the prototype pattern [knight typeknight life speed attack power attack range weaponshort sword [archer typearcher life speed attack power attack range weaponshort bow at the momentthere are only the two units to think aboutbut since you already had moment to contemplate all the other units you are going to add to your...
7,961
the prototype pattern your upgraded unit-generation code would now look like thisrts_multi_unit py class knight(object)def __init__(selflevel)self unit_type "knightif level = self life self speed self attack_power self attack_range self weapon "short swordelif level = self life self speed self attack_power self attack_...
7,962
the prototype pattern if level = self life self speed self attack_power self attack_range self weapon "short bowelif level = self life self speed self attack_power self attack_range self weapon "long bowdef __str__(self)return "type{ }\ "life{ }\ "speed{ }\ "attack power{ }\ "attack range{ }\ "weapon{ }formatself unit_...
7,963
the prototype pattern knight barracks build_unit("knight" archer barracks build_unit("archer" print("[knight {}format(knight )print("[archer {}format(archer )in the results that followyou will see that the code generates level knight and level archerand their individual parameters match what you would expect them to be...
7,964
the prototype pattern digging through hundreds of thousands of lines of code to find values for the parameters of each class and alter themespecially if the developers must do that hundreds of times throughout the development lifecycle imagine what mess digging through lines upon lines of code would be for game like ev...
7,965
the prototype pattern self attack_power lines[ self attack_range lines[ self weapon lines[ def __str__(self)return "type{ }\ "life{ }\ "speed{ }\ "attack power{ }\ "attack range{ }\ "weapon{ }formatself unit_typeself lifeself speedself attack_powerself attack_rangeself weapon class archer(object)def __init__(selflevel)...
7,966
the prototype pattern def __str__(self)return "type{ }\ "life{ }\ "speed{ }\ "attack power{ }\ "attack range{ }\ "weapon{ }formatself unit_typeself lifeself speedself attack_powerself attack_rangeself weapon class barracks(object)def build_unit(selfunit_typelevel)if unit_type ="knight"return knight(levelelif unit_type ...
7,967
the prototype pattern you can verify that your results match these results[knight typeknight life speed attack power attack range weaponshort sword [archer typearcher life speed attack power attack range weaponlong bow players will be able to build multiple versions of the same buildingas we discussed beforeand we want...
7,968
the prototype pattern what we have here is very real need to create large number of objects that are mostly the samewith one or two small tweaks differentiating them loading these objects from scratch every time is not scalable solutionas we saw which brings us to implementing the prototype pattern in the prototype pa...
7,969
the prototype pattern in the rts exampleevery building should keep list of the prototypes it can use to generate unitslike list of units of the same levelwith the properties to match the current state of the building when building is upgradedthis list is updated to match the new capabilities of the building we get to r...
7,970
the prototype pattern what do you expect the results of the print statements to belook at the following output does it match what you expected[ [ [ [ [ [ [ [ most people find it surprising that the digit was appended to the end of both the list points to and the list points to if you remember that in fact and point to ...
7,971
the prototype pattern does the result you see surprise you[ [ [ [ [ [ [ [ the slice operator works perfectly when dealing with shallow list ( list containing only actual valuesnot references to other complex objects like lists or dictionariesdealing with nested structures look at the code that follows what do you thin...
7,972
the prototype pattern were you surprised to see what happenedthe list lst contained three elements' '' 'and pointer to another list that looked like this['ab''ba'when we did shallow copy of lst to create the list that lst points toonly the elements in the list on one level were duplicated the structures contained at th...
7,973
the prototype pattern using what we have learned in our project at its heartthe prototype pattern is just clone(function that accepts an object as an input parameter and returns clone of it the skeleton of prototype pattern implementation should declare an abstract base class that specifies pure virtual clone(method a...
7,974
the prototype pattern class knight(prototype)def __init__(selflevel)self unit_type "knightfilename "{} {datformat(self unit_typelevelwith open(filename' 'as parameter_filelines parameter_file read(split("\ "self life lines[ self speed lines[ self attack_power lines[ self attack_range lines[ self weapon lines[ def __str...
7,975
the prototype pattern with open(filename' 'as parameter_filelines parameter_file read(split("\ "self life lines[ self speed lines[ self attack_power lines[ self attack_range lines[ self weapon lines[ def __str__(self)return "type{ }\ "life{ }\ "speed{ }\ "attack power{ }\ "attack range{ }\ "weapon{ }formatself unit_typ...
7,976
the prototype pattern def build_unit(selfunit_typelevel)return self units[unit_type][levelclone(if __name__ ="__main__"barracks baracks(knight barracks build_unit("knight" archer barracks build_unit("archer" print("[knight {}format(knight )print("[archer {}format(archer )when we extended the abstract base class in the ...
7,977
the prototype pattern add second type of building take look at the pygame package (how can you extend your knight class so it can draw itself in game loopas an exerciseyou can look at the pygame package and implement draw(method for the knight class to be able to draw it on map if you are interestedtry to write your ow...
7,978
factory pattern quality means doing it right when no one is looking --henry ford in you started thinking about writing your own game to make sure you don' feel duped by text-only "game,let' take moment and look at drawing something on the screen in this we will touch on the basics of graphics using python we will use t...
7,979
factory pattern screen obviouslywe want the screen to stay up little longerso let' just add sleep function to graphic_base py graphic_base py import pygame from time import sleep pygame init(screen pygame display set_mode(( )sleep( from the time package (part of the standard librarywe import the sleep functionwhich sus...
7,980
factory pattern if you leave out the pygame display flip()no shape is displayed this is because pygame draws the screen on memory buffer and then flips the whole image onto the active screen (which is what you seeevery time you update the displayyou have to call pygame display flip(to have the changes show up on the sc...
7,981
factory pattern at the momentthis code does nothing but wait for the player to click the close button on the window and then terminate execution to make this more interactivelet' add small square and have it move when the user presses one of the arrow keys for thiswe will need to draw the square on the screen in its in...
7,982
factory pattern shape_game py import pygame class shape(object)def __init__(selfxy)self self def draw(self)raise notimplementederror(def move(selfdirection)if direction ='up'self - elif direction ='down'self + elif direction ='left'self - elif direction ='right'self + class square(shape)def draw(self)pygame draw rectsc...
7,983
factory pattern if __name__ ='__main__'window_dimensions screen pygame display set_mode(window_dimensionssquare square( obj square player_quits false while not player_quitsfor event in pygame event get()if event type =pygame quitplayer_quits true pressed pygame key get_pressed(if pressed[pygame k_up]obj move('up'if pre...
7,984
factory pattern clearlypolymorphism is not complete solutionsince we would have to keep updating code whenever we create new objectand in large game this will happen in many places the issue is the creation of the new types and not the use of these types since you want to write better codethink about the following char...
7,985
factory pattern the factory method when we want to call method such that we pass in string and get as return value new objectwe are essentially calling factory method the type of the object is determined by the string that is passed to the method this makes it easy to extend the code you write by allowing you to add f...
7,986
factory pattern assert "bad shape requestedtype class square(shape)def draw(self)pygame draw rectscreen( )pygame rect(self xself class circle(shape)def draw(self)pygame draw circlescreen( )(selfxself ) if __name__ ='__main__'window_dimensions screen pygame display set_mode(window_dimensionsobj shape factory("square"pla...
7,987
factory pattern screen fill(( )obj draw(pygame display flip(how much easier would it be to adapt this piece of code above to change from square to circleor to any other shape or image you might wantsome advocates of the factory method suggest that all constructors should be private or protected since it should not matt...
7,988
factory pattern class circlefactory(abstractfactory)def make_object(self)do something return circle(class squarefactory(abstractfactory)def make_object(self)do something return square(herewe used the built-in abc modulewhich lets you define an abstract base class the abstract factory defines the blueprint for defining ...
7,989
factory pattern in the barebones game we have set up so faryou could imagine the factory generating objects that contain play(methodwhich you could run in the game loop to play soundscalculate movesor draw shapes and images on the screen another popular use for abstract factories is to create factories for the gui elem...
7,990
factory pattern exercises add the functionality to switch between circletriangleand square via key press try to implement an image object instead of just shape enhance your image object class to switch between separate images to be drawn when moving updownleftand rightrespectively as challengetry to add animation to t...
7,991
builder pattern can he fix ityeshe can--"bob the buildertheme song if you work in software for any amount of timeyou will have to deal with getting input from the user--anything from having player enter their character name in game to adding data to the cells on spreadsheet forms are often the heart of an application a...
7,992
builder pattern basic_form_generator py def generate_webform(field_list)generated_fields "\njoinmaplambda '{ }:format( )field_list return "{fields}format(fields=generated_fieldsif __name__ ="__main__"fields ["name""age""email""telephone"print(generate_webform(fields)in this simplistic examplethe code assumes that the l...
7,993
builder pattern if __name__ ="__main__"fields ["name""age""email""telephone"build_html_form(fieldsas mentioned in the beginning of this webforms (and forms in generalcould have many more field types than simple text fields we could add more field types to the form using named parameters look at the following codewhere ...
7,994
builder pattern if __name__ ="__main__"text_fields ["name""age""email""telephone"checkbox_fields ["awesome""bad"build_html_form(text_field_list=text_fieldscheckbox_field_list=checkbox_ fieldsthere are clear issues with this approachthe first of which is the fact that we cannot deal with fields that have different defa...
7,995
builder pattern generated_fields "\njoin(generated_field_listreturn "{fields}format(fields=generated_fieldsdef build_html_form(field_list)with open("form_file html"' 'as ff write"{}formatgenerate_webform(field_listif __name__ ="__main__"field_list "type""text_field""label""best text you have ever written""name""best_te...
7,996
builder pattern form generator that would generate any form you could imagine by now you should be picking up bad smell stacking loops and conditional statements inside and on top of each other quickly becomes unreadable and unmaintainable let' clean up the code bit we are going to take the meat of each field' generati...
7,997
builder pattern def build_html_form(field_list)with open("form_file html"' 'as ff write"{}formatgenerate_webform(field_listif __name__ ="__main__"field_list "type""text_field""label""best text you have ever written""name""best_text}"type""checkbox""id""check_it""value"" ""label""check for one"}"type""text_field""label"...
7,998
builder pattern oop_html_ form_ generator py class htmlfield(object)def __init__(self**kwargs)self html "if kwargs['field_type'="text_field"self html self construct_text_field(kwargs["label"]kwargs["field_name"]elif kwargs['field_type'="checkbox"self html self construct_checkbox(kwargs["field_id"]kwargs["value"]kwarg...
7,999
builder pattern generated_fields "\njoin(generated_field_listreturn "{fields}format(fields=generated_fieldsdef build_html_form(field_list)with open("form_file html"' 'as ff write"{}formatgenerate_webform(field_listif __name__ ="__main__"field_list "field_type""text_field""label""best text you have ever written""field_n...