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 post is published and notification is sent to all self notifyall(class subscriberdef __init__(self)#make it uninheritable pass def notify(self)#override pass class user (subscriber)def notify(self,postname)print 'user notfied of new post %spostname class user (subscriber)def notify(selfpostname)print 'user notfied of new post %spostname class sistersites(subscriber)def __init__(self)self _sisterwebsites ["site ","site ","site "def notify(selfpostname)for site in self _sisterwebsitessend updates by any means print "sent nofication to site%ssite if __name__ ="__main__"techforum techforum(user user (user user ( www testingperspective com |
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 codesuch as class library facade pattern falls under the hood of structural design patterns facade is nothing but an interface that hides the inside details and complexities of system and provides simplified --front end|to the client with facade patternclient can work with the interface easily and get the job done without being worried of the complex operations being done by the system an important point to understand about the facade pattern is that it provides simplified interface to part of the systemthereby providing ease-of-use for sub-set of the functionality rather than complete functionality beauty of this is that the underlying classes are still available to the client if the client wants additional features/greater control and customization that are not provided in the current context of facade pattern implementation because of the above reasonfacade pattern is not about --encapsulating|the subsystemrather about providing simplified interface for chosen functionality www testingperspective com |
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 we have facadethe class computerthat is exposed to the client with the help of the start(method when the client intends to start the computer systemit calls the start(method of class computer by calling computer start(let' see what actually happens behind the scenesin start()cpumemory and harddrive classes are instantiated then the load(method of class memory is called where it gets the boot_address and calls the read(method of harddrive class from it gets the boot_sector and sector_size of the harddrive start(then calls the jump(method of cpu class with the boot_address and then calls the execute(method thus the client is not aware of the complex operations happening in the background when the computer is started it only has facade exposed to it from where it could start the computer easily without bothering about the inner details or complexities www testingperspective com |
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 test automation framework tests that need to be run for particular build are written in the form of classes namely_tc tc tcneach of these classes contains method called _run()that gets called to execute the test we provide facade testrunner on top these test classes as simplified interface to execute all tests in this mannerthe clientdoesn' need to bother about how many tests really exist and how to execute them the _testrunnerclass has method named _runallthat is responsible for running all the tests that are registered with it now when the user of the automation framework intends to run the tests for buildas clients/he needs to create an object of _testrunnerclass and call the _runallmethod 'runallmethod would inturn create objects of all the test classes and call their 'runmethod thereby executing all tests python code #complex parts import time class tc def run(self)print "#####in test ######time sleep( print "setting uptime sleep( 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( www testingperspective com |
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 tc (self tc tc (def runall(self)self tc run(self tc run(self tc run(#client if __name__ ='__main__'testrunner testrunner(testrunner runall( www testingperspective com |
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 communicating amongst each other to produce result when the software starts getting developedmore user requests get added and in turn more functionality need to be coded this results in increased interaction with in the existing classes and in addition of new classes to address new functionality with the increasing complexity of the systeminteraction between classes becomes tedious to handle and maintaining the code becomes difficult mediator pattern comes in as solution to this problem by allowing loose-coupling between the classesalso called as colleagues in the mediator design pattern the idea is that there would be one mediator class that is aware of the functionality of all the classes in the system the classes are aware of their functionality and interact with the mediator class whenever there is need of interaction between the classesa class sends information to the mediator and it is the responsibility of the mediator to pass this information to the required class thus the complexity occurring because of interaction between the classes gets reduced www testingperspective com |
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 class reporter calls its prepare(method while the test category starts getting executed and calls its report(method when the test category finishes its execution this helps in text based reporting of the tests that are run by the framework class db stores the execution status of the test category by first calling the insert(method while the test category is in setup()and then calls the update(method once the test category has finished execution in this wayat any given point of timethe test execution status is available for framework user to query from the database testmanager class is the one that co-ordinates for test category execution (class tcand fetching the reports (class reporterand getting the test execution status in database (class dbwith the help of preparereporting(and publishreport(methods methods settm()settc()setreporter(and setdb(are used so that the classes could register with each other and can communicate easily building the analogy with the mediator patternthe testmanager class is mediator between class tcclass reporter and class dbthe colleagues in the system let' have look at sample python code which would make the concept more clear python code import time class tcdef __init__(self)self _tm tm self _bproblem def setup(self)print "setting up the test www testingperspective com |
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)self _tm tm def setproblem(selfvalue)self _bproblem value class reporterdef __init__(self)self _tm none def prepare(self)print "reporter class is preparing to report the resultstime sleep( def report(self)print "reporting the results of testtime sleep( def settm(self,tm)self _tm tm class dbdef __init__(self)self _tm none def insert(self)print "inserting the execution begin status in the databasetime sleep( www testingperspective com |
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)rvalue self _db insert(if rvalue =- self _tc setproblem( self _reporter prepare(def setreporter(selfreporter)self _reporter reporter def setdb(selfdb)self _db db def publishreport(self)self _db update(rvalue self _reporter report(def settc(self,tc)self _tc tc if __name__ ='__main__'reporter reporter(db db(tm testmanager(tm setreporter(reportertm setdb(dbreporter settm(tmdb settm(tm www testingperspective com |
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 registers these classes with each other with the help of setreporter()setdb(and settm(methods when the test category starts executionthe testmanager class and the tc class register with each other tc class first calls the setup(method which in turn requests the testmanager class (the mediatorto be prepared for reporting of the test execution results using the preparereporting(method preparereporting(method of the testmanagerthe mediator classcommunicates with the other colleagues (class reporter and class dbin the system by calling the prepare(and insert(methods execute(method of class tc is responsible for running the tests when the test execution is getting finishedteardown(method of class tc is calledwhich in turn calls the publishreport(method of the mediator (class testmanagerwhich communicates with the colleagues (class reporter and class dbfor preparing the report and getting the execution status in the database (by calling the prepare(and update(methods respectivelyalsoduring insert()if communication between class tc (colleagueand class testmanager (mediatorfailsthe next step in test execution is conveyed of this failure by this exampleit can be understood that the communication between colleagues in the system (class tcclass reporter and class dbcan easily be achieved by the mediator (class testmanagerand the possibility of the complexity that could arise as result of communication between colleagues without the mediator is avoided this example also demonstrates the capability of two way interaction between the colleague and the mediator with the help of communication failure case between class tc and class testmanager www testingperspective com |
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 instead of taking decision on which objects get created it defers this creation decision to its subclasses to support this there is creation class hierarchy for the objects which the factory class attempts create and return factory pattern is used in cases when based on --type|got as an input at runtimethe corresponding object has to be created in such situationsimplementing code based on factory pattern can result in scalable and maintainable code to add new typeone need not modify existing classesit involves just addition of new subclasses that correspond to this new type in shortuse factory pattern whena class does not know what kind of object it must create on user' request you want to build an extensible association between this creater class and classes corresponding to objects that it is supposed to create an example would be better way to understand the above context www testingperspective com |
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 that print the salutation message and factory class factory class has method named 'getpersonthat takes two arguments 'nameand 'genderof person the client instantiates the factory class and calls the getperson method with name and gender as arguments during run-timebased on the genderthat is passed by the clientthe factory creates an object of the class pertaining to that gender hence the factory class at run-time decides which object it needs to create python code class persondef __init__(self)self name none self gender none def getname(self)return self name def getgender(self)return self gender class male(person)def __init__(selfname)print "hello mr name class female(person)def __init__(selfname)print "hello miss name class factorydef getperson(selfnamegender)if gender =' 'return male(nameif gender =' 'return female(name www testingperspective com |
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 pattern is reference counting pointer object proxy pattern is an example of structural design patterns it is also referred to as --surrogate|pattern as the intention of this pattern is to create surrogate for the real object/class proxy pattern has three essential elementsreal subject (that performs the business objectivesrepresented by proxyproxy class (that acts as an interface to user requests and shields the real subjectclient (that makes the requests for getting the job donethis design pattern is typically used in situations when creation of object for real subject class is costly in terms of resources and simple object creation by proxy class can be cheaper option www testingperspective com |
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 cache certain set of frequently requested web pages to cater to clients requests this helps in avoiding many requests getting hit on the server and improves performance the message box which gives the status of file copy operation giving the progress in terms of percentage completion opening large file in word processor leads to message saying --please wait while the software opens the document | sample python implementation example description based on the example from prof kiranlet us consider case of regular office situation wherein order to speak to sales manager of companythe client makes call first to the receptionist of the sales manager office and then the receptionist passes the call to the manager in this casesales manager would be the subject to whom the client wants to speak to and the receptionist would be the proxy that shields the subject from talking directly to the clients expanding this examplewe could consider 'sales manageras the real subject and create common subject class referred to as 'managersfrom which 'sales managerand the 'receptionistcan be derived python code import time class manager(object)def work(self)pass def talk(self)pass class salesmanager(manager)def work(self)print "sales manager working www testingperspective com |
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 parting shots exercises command pattern controlling the turtle the command pattern parting shots exercises interpreter pattern domain-specific languages advantages of dsls disadvantages of dsls composite pattern internal dsl implementation using the composite pattern |
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 method pattern parting shots exercises visitor pattern the visitor pattern parting shots exercises |
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 proxy chain of responsibility alternative command composite interpreter iterator alternative |
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 with all thingsyou will soon see that as the supply of programmers increasesthe cost of hiring programmers will decrease simply being able to write few lines of code or change something in piece of software will (like the role of spreadsheet or word-processing gurubecome basic skill if you plan on making living as programmerthis problem is made worse by the internet you have to worry not only about programmers in your own areabut also those from all over the world do you know who does not worry about the millions of programmers produced by the hundreds of code boot camps that seem to spring up like mushroomsthe masters while everyone can writethere are still the hemingways of the world while everyone can work excelthere are still the financial modelers and when everyone can codethere will still be the peter norvigs of the world programming is tool for timesimply knowing how to use this tool made you valuable that time has come to an end there is new realitythe same one that lot of industries have had to face over the years when tool is newno one wants to use it thensome see the valueand it makes them twice as good as the ones who can' use the tool thenit becomes popular before you know iteveryone can use the internet (cwessel badenhorst badenhorstpractical python design patterns |
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 outproduce the average person on every level--quality of workspeed of developmentand the beauty of the final result right nowwe see the popular uptake of that which is easy the next step will be automating what is easy easy tasksin every area of lifeare easy because they do not require creativity and deep understandingand as result of these characteristics they are the exact tasks that will be handed over to computers first the reason you picked up this book is because you want to become better programmer you want to progress beyond the thousands of introductions to this and that you are ready to take the next stepto master the craft in the new world of programmingyou want to be able to solve bigcomplex problems to do thatyou need to be able to think on higher level just like the chess grand-masterswho can digest the game in larger chunks than mere mastersyou too need to develop the skill to solve problems in larger chunks when you are able to look at brand-new problem and rapidly deconstruct it into high-level partsparts you have solved beforeyou become an exponential programmer when began programmingi could not read the manual yet there was picture of space invaders on the coverand it promised to teach you how to program game yourself it was bit of racket because the game ended up being for loop and single if statementnot space invaders but was in love passion drove me to learn everything could about programmingwhich was not lot after mastering the basicsi stagnatedeven while attaining bs in computer science (cum laudi felt like what was learning was simple rehashing of the basics did learnbut it felt slow and frustratinglike everybody was waiting for something in the "real world,it did not look lot different came to realize that if wanted to become an exponential programmeri had to do something different at firsti thought about getting master' degree or ph but in the end decided to dig deeper on my own reread the old theory of computing booksand they gained new meaning and new life started regularly taking part in coding challenges and studied more idiomatic ways of writing code theni began exploring programming languages and paradigms foreign to my own before knew iti was completely transformed in my thinking about programming problems that used to be hard became trivialand some that seemed impossible became merely challenging |
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 different frameworks and languages and figure out what makes them great once you can understand what makes someone love different language than the one you use regularlyyou may find couple of ideas in it that you can integrate into your way of thinking study recipes and patterns wherever you find them and translate them into an abstract solution that you can use over and over sometimesyou can simply analyze solution you already usecan you find more elegant way to implement the ideaor is the idea flawed in some wayconstantly ask yourself how you can improve your toolsyour skillsor yourself if you are ready to dig deep and master the artyou will find ideas in this book that will guide you along the road to mastery we are going to explore set of fundamental design patterns in real-world context while you are doing thisyou will begin to realize how these design patterns can be seen as building blocks you can use when you encounter specific type of problem in the future my hope is that you will use the design patterns in this book as blueprintthat it will help you kick-start your own collection of problem-solution chunks after you have read this bookyou should be well on your way to reaching the next level in your journey as programmer you should also see how this set of abstract tools can be translated into any programming language you may encounterand how you can use ideas and solutions from other languages and incorporate them into your mental toolbox becoming better programmer to become better programmeryou need to decide to obsess about mastery every day is new opportunity to become better than the day before every line of code is an opportunity to improve how do you do thatwhen you must work on piece of existing codeleave the code better than you found it try to complete quick problem-solving challenge every day look for opportunities to work with people who are better programmers than you are (open source projects are great for this |
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 call mastery he found that these people had couple of things in common the firstas popularized in malcolm gladwell' book outlierswas that these people all seemed to have spent significant amount of time working on the skill in question the actual numbers varybut the time invested approached about , hours that is significant amount of timebut simply spending , hoursor ten yearspracticing is not enough there is very specific type of practice that was shown to be required for master-level performance the key to world-dominating skill is deliberate practice we will look at how this relates to programming in momentbut let' first look at what deliberate practice is deliberate practice is slowhaltinganti-flow if you are practicing the violindeliberate practice would entail playing the piece extremely slowlymaking sure you hit every note perfectly if you are deliberately practicing tennisthis might mean doing the same shot over and over and over again with coachmaking small adjustments until you are able to perfectly hit that shot in that location time and time again the problem with knowledge work is that the standard deliberate practice protocols seem foreign sports task or playing an instrument is fairly simple when compared to the process involved in programming it is lot harder to deconstruct the process of designing and developing software solution it is hard to figure out how to practice way of thinking one of the reasons for this is that solved problem tends to stay solved what mean by that is that as developer you will very rarely be asked to write piece of software that has already been written finding the "shotto practice over and over is hard |
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 practice has these componentseach practice session has single focus the distance (timebetween attempt and feedback is as short as possible work on something that you cannot yet do follow in the path of those who have gone before you single focus the reason you only want to focus on one thing during specific training session is that you want devote all your attention to the element that you wish to improve you want to do whatever it takes to do it perfectlyeven if it is only once thenyou want to repeat the process to get another perfect responseand then another every practice run is single reinforcement of the skill you want to reinforce the patterns that lead to the perfect result rather than those that have less desirable outcomes in the context of this booki want you to target single design pattern at time really seek to understand not only how the pattern worksbut also why it is used in the first place and how it applies to the problem at hand alsothink about other problems that you might be able to solve using this design pattern nexttry to solve some of these problems using the pattern you are working on you want to create mental box for the problem and the pattern that solves it ideallyyou will develop sense for when problems would fit into one of the boxes you have masteredand then be able to quickly and easily solve the problem rapid feedback one of the pieces of deliberate practice that is often overlooked is the rapid-feedback loop the quicker the feedbackthe stronger the connectionand the more easily you learn from it that is why things like marketing and writing are so hard to master the time between putting letters on page and getting feedback from the market is simply |
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 codeyou get even more feedbackand you are able to arrive at the solution much more quickly than if you had to test the process manually each time you made change another trick to help you learn from the process more rapidly is to make prediction as to what the outcome of the block of code you want to write will be make note as to why you expect this specific outcome now write the code and check the result against the expected result if it does not match uptry to explain why this is the case and how you would verify your explanation with another block of code thentest that keep doing it until you have attained mastery you will find yourself getting feedback on different levelsand each has its own merit level one is simply whether the solution works or not nextyou might begin considering questions such as "how easy was the solution to implement?or "is this solution good fit for the problem?lateryou might seek out external feedbackwhich can take the form of simple code reviewworking on projectsor discussing solutions with like-minded people stretch yourself what are the things that you shy away fromthese are the areas of programming that cause you slight discomfort it might be reading from file on disk or connecting to remote api it makes no difference if it is some graphical library or machine-learning setupwe all have some part of the craft that just does not sit comfortably these are usually the things that you most need to work on here are the areas that will stretch you and force you to face your own weaknesses and blind spots the only way to get over this discomfort is to dive deep into itto use that tool so many times and in so many ways that you begin to get feel for it you must get so comfortable with it that you no longer have to look up that file open protocol on stack overflowin factyou have written better one you jump rope with the gui and suck data out of database with one hand tied behind your back there is no shortcut to this level of masterythe only way is through the mountain that is why so few people become true masters getting there means spending lot of time on the things that are not easythat do not make you feel like you are invincible you spend so much time in these ego-destroying zones that very few masters of any craft have lot of arrogance left in them |
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 giants there are people who do amazing things in the programming space these people often give talks at developer conferences and sometimes have presence online look at what these people are talking about try to understand how they approach novel problem type along with them as they demonstrate solutions get into their head and figure out what makes them tick try to solve problem like you imagine one of them would do ithow does the solution you come up with in this way differ from the one you came up with on your ownreally great developers are passionate about programmingand it should not take lot of prodding to get them to talk about the finer details of the craft seek out the user groups where this type of developer hangs out and strike up lot of conversations be open and keep learning pick personal projects that force you to use design patterns you have yet to master have fun with it most of alllearn to love the processand don' get caught up on some perceived outcome rather than spending time becoming better programmer how do you do thisbegin the same way leonardo da vinci began when he decided to make painting his vocation copythat is right begin by identifying some interesting problemone that is already solvedand then blatantly copy the solution don' copy/paste copy the solution by typing it out yourself get your copy to work once you dodelete it all now try to solve the problem from memoryonly referring to the original solution when your memory fails you do this until you are able to reproduce the solution flawlessly without looking at the original solution if you are looking for solutions to problems that you can copy and learn fromgithub is gold mine |
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 these ways nextyou want to take your new solution out into the wild find places to use the solution practicing in the real world forces you to deal with different constraintsthe kinds you would never dream up for yourself it will force you to bend your niceclean solution in ways it was never intended to be sometimesyour code will breakand you will learn to appreciate the way the problem was solved originally other timesyou may find that your solution works better than the original ask yourself why one solution outperforms anotherand what that teaches you about the problem and the solution try using languages with different paradigms to solve similar problemstaking from each and shaping solution yourself if you pay attention to the process as much as you do to actually solving the problemno project will leave you untouched the beauty of working on open source projects is that there is usually just the right mix of people who will help you alongand others who will tell you exactly what is wrong with your code evaluate their feedbacklearn what you canand discard the rest the ability to course correct when exploring problemyou have two optionsgo on trying this wayor scrap everything and start over with what have learned daniel kahnamannin his book thinkingfast and slowexplains the sunk cost fallacy it is where you keep investing in poor investment because you have already invested so much in it this is deadly trap for developer the quickest way to make two-day project take several months is to try to power your way through poor solution often it feels like it would be massive loss if we were to scrap daya weekor month' work and start from nothing the reality is that we are never starting from scratchand sometimes the last , lines of code you are deleting are the , lines of code you needed to write to become the programmer you need to be to solve the problem in lines of code with startlingly elegant solution you need to develop the mental fortitude to say enough is enough and start overbuilding new solution using what you have learned no amount of time spent on solution means anything if it is the wrong solution the sooner you realize that the better |
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 learning to deconstruct and understand systemsyou inevitably teach yourself how to design and build systems every piece of software out there is an expression of these three core componentsthe elements that make up the solutionand set of connections and interactions between them at very basic levelyou can begin by asking yourself"what are the elements of the system want to build?write these down thenwrite down how they are connected to each other lastlylist all the interactions between these elements and what connections come into play do thisand you will have designed the system all design patterns deal with these three fundamental questions what are the elements and how are they created what are the connections between elementsor what does the structure look like how do the elements interactor what does their behavior look likethere are other ways to classify design patternsbut for now use the classical three groupings to help you develop your systems thinking skills mental models mental models are internal representations of the external world the more accurate your models of the world arethe more effective your thinking is the map is not the territoryso having more-accurate mental models makes your view of the world more accurateand the more versatile your set of mental models isthe more diverse the set of problems you will be able to solve throughout this book you will learn set of mental tools that will help you solve specific programming problems you will regularly come across in your career as programmer another way to look at mental models is to see them as grouping of concepts into single unit of thought the study of design patterns will aid you in developing new mental models the structure of problem will suggest the kind of solution you will need to implement in order to solve the problem in question that is why it is important that you gain complete clarity into exactly what the problem is you are trying to solve |
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 statementto (the solutionwithout having to go through and however many other false starts the right tools for the job to break down brick wallyou need hammerbut not just any hammer--you need bigheavy hammer with long handle sureyou can break down the wall with the same hammer you would use to put nails in music boxbut it will take you couple of lifetimes to do what an afternoon' worth of hammering with the right tool will do with the wrong toolsany job becomes mess and takes way longer than it should selecting the right tool for the job is matter of experience if you had no idea that there were hammers other than the tiny craft hammer you were used toyou would have hard time imagining that someone could come along and take down whole wall in couple of hours you might even call such person wall breaker the point am trying to make is that with the right tool you will be able to do many times more work than someone who is trying to make do with what they have it is worth the time and effort to expand your toolboxand to master different toolsso that when you encounter novel problem you will know which to select to become master programmeryou need to consistently add new tools to your arsenalnot just familiarizing yourself with thembut mastering them we already looked at the process for attaining mastery of the tools you decide onbut in the context of pythonlet me make some specific suggestions some of the beauties of the python ecosystem are the packages available right out of the gate there are lot of packagesbut more often than not you have one or two clear leaders for every type of problem you might encounter these packages are valuable toolsand you should spend couple of hours every week exploring them once you have mastered the patterns in this bookgrab numpy or scipy and master them thenhead off in any direction your imagination carries you download the package you are interested inlearn the basicsand then begin experimenting with it using the frameworks touched on already where do they shineand what is missingwhat kinds of problems are they especially good at solvinghow can you use them in the futurewhat side project can you do that will allow you to try the package in question in realworld scenario |
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 number of languages the goal of the design patterns set forth in that book was to codify best-practice solutions to common problems encountered in object-oriented programming as suchthe solutions focus on classes and their methods and attributes these design patterns represent single complete solution idea eachand they keep the things that change separate from the things that do not there are many people who are critical of the original design patterns one of these criticspeter norvigshowed how of the patterns could be replaced by language constructs in lisp many of these replacements are possible in python too in this bookwe are going to look at several of the original design patterns and how they fit into real-world projects we will also consider arguments about them in the context of the python languagesometimes discarding the pattern for solution that comes stock standard with the languagesometimes altering the gof solution to take advantage of the power and expressiveness of pythonand other times simply implementing the original solution in pythonic way what makes design patterndesign patterns can be lot of thingsbut they all contain the following elements (creditpeter norvigpattern name intent/purpose aliases motivation/context problem solution structure participants |
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 not all follow this structure classification design patterns are classified into different groupings to help us as programmers talk about categories of solutions with one another and to give us common language when discussing these solutions this allows us to communicate clearly and to be expressive in our discussions around the subject as mentioned earlier in this we are going to classify design patterns according to the original groupings of creationalstructuraland behavioral patterns this is done not only to stick to the general way things are donebut also to aid youthe readerin looking at the patterns in the context of the systems they are found in creational the first category deals with the elements in the system--specificallyhow they are created as we are dealing with object-oriented programmingthe creation of objects happens through class instantiation as you will soon seethere are different characteristics that are desirable when it comes to solving specific problemsand the way in which an object is created has significant effect on these characteristics structural the structural patterns deal with how classes and objects are composed objects can be composed using inheritance to obtain new functionality |
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 be able to make most of the code work with python without much trouble (this is less due to the code in the book and more result of the brilliant work done by the python core developerswith pythoncpython (the default onespecificallyyou get to use pipthe python package installer pip integrates with pypithe python package indexand lets you download and install package from the package index without manually downloading the packageuncompressing itrunning python setup py install and so on pip makes installing libraries for your environment joy pip also deals with all the dependencies for youso no need to run around after required packages you have not installed yet by the time you begin working on your third projectyou are going to need lot of packages not all of these packages are needed for all of your projects you will want to keep every project' packages nicely contained enter virtualenva virtual python interpreter that isolates the packages installed for that interpreter from others on the system you get to keep each project in its own minimalist spaceonly installing the packages it needs in order to workwithout interfering with the other projects you may be working on how to read this book there are many ways to read bookespecially programming book most people start book like this hoping to read it from cover to cover and end up just jumping from code example to code example we have all done it with that in mindthere are ways you can read this book and gain optimal value from the time spent on it the first group of readers just wants quickrobust reference of pythonic versions of the gof design patterns if this is youskip ahead to appendix to see the formal definition of each of the design patterns when you have timeyou can then return to the relevant and follow the exploration of the design pattern you are interested in |
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 group wants to use this book to master their craft for these readersi suggest you begin at the beginning and code your way through the book type out every example tinker with every solution do all the exercises see what happens when you alter the code what breaksand whymake the solutions better tackle one pattern at time and master it thenfind other real-world contexts where you can apply your new knowledge setting up your python environment let' begin by getting working python environment running on your machine in this sectionwe will look at installing python on linuxmacand windows on linux the commands we use are for ubuntu with the apt package manager for other distributions that do not work with aptyou can look at the process for installing python and pip using an alternative package managerlike yumor installing the relevant packages from source the whole installation process will make use of the terminalso you can go ahead and open it up now let' begin by checking if you have version of python already installed on your system just notefor the duration of this booki will indicate terminal commands with the leading $you do not type this character or the subsequent space when entering the comment in your terminal python --version if you have python (as is the case with ubuntu and upalready installedyou can skip ahead to the section on installing pip if you have either python or no python installed on your systemyou can go ahead and install python using the following commandsudo apt-get install python -dev |
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 workingpip --version you should see version of pip installed on your systemand now you are ready to install the virtualenv packageplease skip past the mac and windows installation instructions mac macos comes with version of python installed by defaultbut we will not be needing this to install python we are going to use homebrewa command-line package manager for macos for this to workwe will need xcodewhich you can get for free from the mac appstore once you have installed xcodeopen the terminal app and install the command-line tools for xcodexcode-select --install simply follow the prompt in the window that pops up to install the command-line tools for xcode once that is doneyou can install homebrewruby - "$(curl -fssl master/install)if you do not have xquartz already installedyour macos might encounter some errors if this happensyou can download the xquartz dmg hereorgthencheck that you have successfully installed homebrew and that it is workingbrew doctor |
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 included in the environmentand now you can call brew from anywhere use brew to find the available packages for pythonbrew search python you will now see all the python-related packagespython being one of them nowinstall python using the following brew commandbrew install python finallyyou can check that python is installed and workingpython --version when you install python with homebrewyou also install the corresponding package manager (pip)setuptoolsand pyvenv (an alternative to virtualenvbut for this book you will only need pipcheck that pip is workingpip --version if you see the version informationit means that pip was successfully installed on your systemand you can skip past the windows installation section to the section on using pip to install virtualenv windows begin by downloading the python windows installer you can download the installer herewhen your download is donerun the installer and select the customize option make sure that pip is selected to be installed alsoselect the option to add python to your environment variables |
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 terminal similar to the ones available on mac and linux nowcheck that python is workingpython --version if you see version informationpython is installed and linked to the pathas it should be before we go oncheck that pip is workingpip --version virtualenv before we begin installing virtualenvlet' make sure we have the latest version of pip installedpip install --upgrade pip windows users will see command prompt like thisc:\some\directoryon mac you have on linux it is will be using to indicate terminal commands for the duration of this book use pip to install the virtualenv packagepip install virtualenv |
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 ppdpenvthe env is just so we know that it is virtual environment whenever we have this environment active and install new package using the pip commandthe new package will only be installed in this environmentand will only be available to programs while this environment is active virtualenv - python ppdpenv on windowsyou need slightly different commandvirtualenv - python ppdpenv if python is not part of your pathyou can use the full path to the python executable you want to use inside your virtualenv after the installation process is concludedyou will have new directory named ppdpenv in the directory you were in when you ran the virtualenv command to activate the virtual environmentrun the following command on mac and linuxsource /ppdpenv/bin/activate and on windowssource ppdpenv\scripts\activate lastlycheck the version of python to make sure that the right version is installed that' it--you are all set up and ready to program in pythonto exit the virtual environmentyou run the following commanddeactivate editors any text editor that can save plain text files can be used to write python programs you could write the next uber using nothing but notepadbut it would be painful whenever you write program of any lengthyou want an editor that highlights your codemarking different keywords and expressions with different colors so you can easily differentiate between them |
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 it is based on electron means that you can take your editor with you no matter what platform you want to work on if it can run chromiumit will run atom get it herelighttable this one is based on clojurescript ( lisp dialect that compiles down to javascriptwith both vim and emacs modesso you can free yourself from the mouse like most modern code editorslighttable also offers direct git integration it is open source and easy to customize get it herep ycharm jetbrains made the industry standard when it comes to python editors it comes with great code completionpython linterunused import warningsand whole lot morebut for me the killer feature is the code spell checking that takes both camel and snake case into consideration the enterprise edition of pycharm is not cheapbut they offer free student and community licenses get it herev im most unix-based operating systems come with vim already installed vim is sometimes called the editor you can' get out of (tip": !gets you outwhat gives vim most of its power is that its shortcut keys do everything from selecting blocks to jumping to specific lines in code--everything without taking your hands off of the keyboard over |
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 learn--very hard use vim whenever want to write quick script or make small change and do not want to wait for some other editor/ide to start up set up vim for python by going hereand-python- -match-made-in-heavenemacs an amazing operating systemif only it had good text editor emacs is built on emacs lisp and is insanely customizable you can do anything with itfrom sending emails to having your coffee machine startwith simple shortcut key combination like vimit is mouse freebut it has an even steeper learning curve those in the know swear by itand with good reason you have all the code-completion and split-screen options that modern ide offers with the ability to adapt the system as and when you feel the need to you do not have to wait for some vendor to create package to handle some new language featureyou can easily do it yourself easily is used very loosely with emacs you can make your editor do things the way you feel they ought to be doneand large part of programming is being dissatisfied with the way things are currently done and taking it upon yourself to do it differently set up emacs for python development by reading thisblog/python/emacs-the-best-python-editors ublime text this is more of an honorable mention than real suggestion sublime used to be the best free (with nag screens every couple of savesoption available it has beautiful default color schemeis fairly quick to startand is extensible it comes python-readybut its time has probably passed if you are interested in looking at ityou can get it herecom/ |
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 is that you pick one of these to learn inside outand if it is not vim or emacsat least learn enough vim to edit text in it it will make the time you spend on servers editing software much more enjoyable nowyou have your environment set up and isolated from the rest of your system you also have your editor of choice installed and ready to goso let' not waste any time let' start looking at some practical python design patterns |
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 cannot run the whole program in your mind effectively this is when you need to print out the values of certain variables at specific timesespecially when the program does not act as you expect it to looking at the output of your program at different points in its execution helps you locate and fix bugs swiftly your code quickly becomes littered with print statementsand that' fineuntil one fine day when you deploy your code running your code on serveras scheduled job on your own machineor as standalone piece of software on client' computer means that you can no longer rely on the console for feedback when something goes wrong you have no way of knowing what went wrong or how to replicate the issue this takes debugging from the realm of science straight into gambling the simplest solution is to replace print statements with command to write the output to file instead of to the consolelike thiswith open("filename log"" "as log_filelog_file write("log message goes here \ "(cwessel badenhorst badenhorstpractical python design patterns |
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 looking for bug one line is better than twoso create function that handles opening and writing to the filedef log_message(msg)with open("filename log"" "as log_filelog_file write("{ }\nformat(msg)you can use this replacement for print statements wherever you want to record some state of your program for later reviewlog_message("save this for later"the log_message function opens file and appends the message passed to it to the file this is the dry principle in action dryyou ask it stands for don' repeat yourself at the most basic levelyou should hear little alarm go off in your mind whenever you feel tempted to copy and paste code whenever possibleyou should repackage the code in such way that you can reuse it without the need to copy and paste the lines somewhere else why should you go through the effort of rethinking code that workswhy not copy it and just change one or two piecesif your code is in one placeand you must change somethingyou only have to change it at that one place iffor instanceyou had the code for the logger scattered throughout your programand you decided to change the name of the file you write the logs toyou would have to change the name in many places you will find that this is recipe for disasterif you miss one line of output codesome of your log messages will go missing in programmingthe number one cause of mistakes is people if you need to work on project that spans thousands or even millions of lines of codeand you need to change something like log file nameyou can easily miss line here or there during your update whenever possibleeliminate the number of human interactions with your code good programmers write solid codegreat programmers write code that makes average programmers produce solid code one way of making the code bit more user-friendly is to have file in your project that contains nothing but the logging function this allows you to import the logging function into any file in your project all changes to the way logging is done in the project need only be made in this one file |
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_script py import logger for in range( )logger log_message("log message {}format( )the first line of the file-import logger tells python to import the logger py file (note that you do not add py when you import the fileimporting file allows you to use the functions defined in the logger py file in the main_script py file in the preceding code snippetwe have loop where we tell python to write message log message every time the loop runswhere is the index of the loop in the range open the filename log file and verify that the messages were indeed written as expected as the number of log messages increasesyou will find you want to distinguish between them the most useful distinction is the terms used to describe the severity of the event causing the message in question for the sake of our loggerwe will handle the following levelscritical error warning info debug luckilywe only have single file to update (aren' you glad we moved this logger to its own file? |
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 after upgrading our logging functionit looks like thislogger py def critical(msg)with open("/var/log/filename log"" "as log_filelog_file write("[critical{ }\nformat(msg)def error(msg)with open("/var/log/filename log"" "as log_filelog_file write("[error{ }\nformat(msg)def warn(msg)with open("/var/log/filename log"" "as log_filelog_file write("[warn{ }\nformat(msg)def info(msg)with open("/var/log/filename log"" "as log_filelog_file write("[info{ }\nformat(msg)def debug(msg)with open("/var/log/filename log"" "as log_filelog_file write("[debug{ }\nformat(msg)you do not need to change the way you import the codeyou just use the level of message you want to saveas followstest_error_log py import logger trya exceptlogger error("something went wrong" |
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 is written that alarm bell in your head just went offdid it notif it didyou are completely rightwe should not be copying the same instructions to open the file and append the message to the filewith only the prefix string differing for each function let' refactor our code so we don' repeat ourselves the part that is repeated is the part we want to extract from all the methods duplicating the code the next step is to generalize the function enough so that every function can use it without losing any of its original functionality in each of the repeated functionsthe prefix was the only thing that differed from function to function soif we were to write function that takes the message and level as parameterswe could use this function in each of the other functions and reduce it to single line of code in each case we now have shorterclearer logger to use in our other projects logger py def write_log(levelmsg)with open("/var/log/filename log"" "as log_filelog_file write("[{ }{ }\nformat(levelmsg)def critical(msg)write_log("critical",msgdef error(msg)write_log("error"msgdef warn(msg)write_log("warn"msgdef info(msg)write_log("info"msgdef debug(msg)write_log("debug"msg |
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 our little loggerbut what bothers me most at the moment is that hardcoded filename log that we use to persist all our log files in you now know that logging makes you better developer and saves you lot of time sothis being such nice loggeryou are sure to want to use it in several of your own projects the last thing you want your logger to do is to write messages from different projects to the same file to circumvent this issuewe could just add the file name as parameter on the functions we call when logging our messages go ahead and implement this change note that the following code snippet is still incompleteas the write_log function still takes filename parameter logger py def write_log(filenamelevelmsg)with open(filename" "as log_filelog_file write("[{ }{ }\nformat(levelmsg)def critical(msg)write_log("critical",msgdef error(msg)write_log("error"msgdef warn(msg)write_log("warn"msgdef info(msg)write_log("info"msgdef debug(msg)write_log("debug"msgthe filename parameter does not change from call to callso passing the same value over and over is not the right way to do things the very reason we extracted the write_log function from the other functions is so that we would not have to repeat the same code we want to set up the logger oncewith the log file it should be logging toand then use it without paying any more attention to the selection of the file to write to |
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 data that relate to each other into class forms blueprint for creating specific instances (versionof the data combined with their associated functions an instance of class is called an object to help you understand thisconsider for moment the logger we have just developed if we were able to generalize this logger in such way that we could send it the name of the file to use when we use itwe would have blueprint to create any logger ( classthe moment we make this callwe effectively create new logger that writes to specific file this new logger is called an instance of the class thinking about data and the functions that alter the data as single entity is the basis for object-oriented programming we will now implement simple logger class as an example logger_class py class logger(object)""" file-based message logger with the following properties attributesfile_namea string representing the full path of the log file to which this logger will write its messages ""def __init__(selffile_name)"""return logger object whose file_name is *file_name*""self file_name file_name def _write_log(selflevelmsg)"""writes message to the file_name for specific logger instance""with open(self file_name" "as log_filelog_file write("[{ }{ }\nformat(levelmsg)def critical(selflevelmsg)self _write_log("critical",msg |
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 is implemented in another project the first big departure from our previous logger is the addition of the class keywordwhich acts like the def keyword in that it tells python that we are now going to define new class thenwe have the class namewhich we will use when we want to create new object of this class (called an instanceas you might have guessedone of the main benefits of object-oriented programming (oopis that once you define classyou are able to reuse the class to create other classes this process is called inheritancesince the child class inherits the traits (data and function blueprintfrom the parent class (the class that is used to create the childin pythonevery class ultimately inherits from the object class in the case of our loggerwe have no other class we are using as baseso here we just say that logger only has object as its parent nextwe have bit of text wrapped in ""charactersdenoting that the text contained is doc string certain integrated development environments (idesand other programs know to look for these strings and use them to help guide programmers who want to use this class classes are not the only structures that can make use of doc stringand you will also see that functions can have their own doc stringslike the __init__ function the __init__ is called whenever new logger object is instantiated in this caseit takes the name of file as an argument and associates that with the instance that is being created when we want to reference this file namewe have to tell the method in the object to look for the file_name in its own list of attributes the self keyword is used to let the code know we are referring to an attribute or method associated with an object from which the call is madeandas suchit should not be looking somewhere else for these elements |
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 thisself some_method(what is really happening is that the python interpreter calls the method some_method and passes the object itself as variable into the functionwhich is why you have self as parameter in the methods of the objectbut do not explicitly pass it in when making the call another thing to note is that when referencing an attribute in an objectas in self some_attribute what python does is call method called __getattr__ and pass in the object itself together with the attribute name that it is requesting you will see an example of this soon in the __init__ methodyou will see that we set an attribute called file_name this allows us to request the value of the file_name attribute that we set when we first created the class whenever we want to use the _write_log method the rest is close to what we had beforewith the exception that we now also must make provision for the self parameterwhich we discussed as matter of good practicethe result of the __init__ method must be fully initialized object what that means is that the object must be ready for useit should not require some other settings to be tweaked or methods to be executed before it can perform its function if you are wondering about the leading underscore in _write_logit is just convention to tell other programmers that this method should not be used by any outside programit is said to be private nowwe can look at how this new logger class of ours will be used new_script_with_logger py from logger_class import logger logger_object logger("/var/log/class_logger log"logger_object info("this is an info message" |
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 packages are groups of python files that live in the same folder on your computer and provide similar or related functions to create new logger using the logger blueprint (class)we simply use name for the logger and set that equal to the class nameand then we pass in any parameters needed by the __init__ function after instantiating the loggerwe can simply use the object name with the relevant log function to write the log message to the correct file running new_script_with_logger py will result in the following message in the /var/log/class_logger log file[infothis is an info message cleaning it up nowyou probably do not want to write to unique log file for every part of your project that needs to write some log messages sowhat you want is some way to get the same logger that you already created if there is oneor create new logger if none already exist you want to keep the benefits of object-oriented programming while taking control of the object-creation process out of the hands of the programmer using the logger we do that by taking control of the process by which the logger object is created consider the following way of taking control of the processsingleton_object py class singletonobject(object)class __singletonobject()def __init__(self)self val none def __str__(self)return "{ ! { }format(selfself valthe rest of the class definition will follow hereas per the previous logging script instance none |
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 happening here let' walk through the code and see how this results in single instance of class being createdor being returned whenever the class is instantiated the elephant in the room is the class definition inside our singletonobject class the leading underscores tell other programmers that this is private classand they should not be using it outside of the original class definition the private class is where we implement the functionality of the loggerwhich is left to you as an exercise at the end of the for the sake of the examplethis class has an object attribute called val and two methods__init__which instantiates the objectand __str__which is called when you use the object in print statement nextwe see something called class attribute instancewhich is fixed for all objects instantiated from the singletonobject class this attribute is set to nonewhich means that when the script starts to execute there is no value for the instance the other thing we are not used to seeing is the use of the cls parameter and having no self parameter in the definition of the __new__ function this is because __new__ is class method instead of taking the object as parameterit receives the class as parameter and then uses the class definition to construct new instance of the class by now you have seen number of these methods with two leading and two trailing underscores what you need to know is that in the cases you have encountered up to nowthese were used to indicate that these are magic methodswhich are methods used by the python interpreter without your calling them explicitly |
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 and assigns it to the instance class variable finallythe __new__ function returns the class in the instance class variable we also alter the __getattr__ and __setattr__ functions to call the attributes found in the private class saved in the instance class variable this relays the call to the object housed in the instance variable as if the outer object has the attributes the self val attribute is set just to show that the object remains the same even though the script attempts to instantiate it more than once good--now you can use the class to verify that the singleton implementation does what you would expect it to do test_singleton py from singleton_object import singletonobject obj singletonobject(obj val "object value print("print obj "obj print(""obj singletonobject(obj val "object value print("print obj "obj print("print obj "obj here is the outputprint obj <__main__ singletonobject __singletonobject object at fda def object value ----print obj <__main__ singletonobject __singletonobject object at fda def object value print obj <__main__ singletonobject __singletonobject object at fda def object value |
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 unexpected results in completely unrelated piece of code that saidwhen you have parts of project that do not affect the execution of your codelike loggingit is acceptable to use global state other places where global state may be used are in cachingload balancingand route mapping in all these casesinformation flows in one directionand the singleton instance itself is immutable (it does not changeno part of the program attempts to make change in the singletonand as such there is no danger of one part of project interfering with another part of the project because of the shared state there you have it--you have discovered your first design patternwhich is called the singleton pattern congratulationsexercises implement your own logger singleton how would you create logger using the singleton pattern(creditinspiration for the singleton pattern code template was sparked by the singleton pattern implementation on readthedocs io/en/latest/singleton html cc-by-sa |
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 was beige olivetti xt the local library had section with computer books in it one of thema very thin softcoverhad picture of game character on it the title promised to teach you to program your very own games in classic case of youthful ignorance swayed by false advertisingi worked through every exampletyping out the characters one by one ( could not read english at the timeso really had no idea what was doingafter about the tenth timei got everything entered correctly into the gw basic interface that came with the computer did not know about saving and loading programsso every mistake meant starting from scratch my crowning moment fell completely flat the "gamei had worked so hard on turned out to be simple for loop and an if statement the premise of the game was that you were in runaway car and got three chances to guess number before the car ended up in dam that was it-no graphicsno soundno pretty colorsjust the same text question three times and then"you are dead getting it right resulted in simple message"yayyou got it right beyond the first steps even though my first program was complete let-downthat magical moment when picked up the book for the first time and believed that could program gameor anything could dream ofstuck with me (cwessel badenhorst badenhorstpractical python design patterns |
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 endrelatively few programmers pursue their initial interest in game programming in this we will imagine that we are indeed part of this select group of programmers base for an actual game suppose we want to write an rts (short for real-time strategy gamelike starcraftwhere you have player that controls group of characters the player needs to construct buildingsgenerate unitsand ultimately meet some sort of strategic objective let' consider one unita knight the knight is produced in building called the barracks player can have multiple such buildings in single scenario so as to create knight units more rapidly looking at this description of the unit and its interaction with the buildinga fairly obvious solution would involve defining barracks class that has generate_knight function that returns knight objectwhich is an instance of the knight class we will be implementing the following basic properties for the knight classlife speed attack power attack range weapon generating new knight instance would simply involve instantiating an object from the knight class and setting the values here is the code for doing exactly thatrts_simple py class knight(object)def __init__selflife |
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_rangeself weapon class barracks(object)def generate_knight(self)return knight( "short sword"if __name__ ="__main__"barracks barracks(knight barracks generate_knight(print("[knight {}format(knight )running this code from the command line will create barracks instance of the barracks classand will then use that instance to generate knight which is just an instance of the knight class with values set for the properties we defined in the previous section running the code prints the following text to the terminal so you can check that the knight instance matches what you expect it to be based on the values set in the generate_knight function |
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 us about creating multiple objects that are almost exactly alike note if you are interested in learning more about game programmingi challenge you to look at the pygame packagesee the "exercisessection of this for more information if you have never played or seen an rts beforeit is important to know that big part of the fun in these games comes from the many different units you can generate each unit has its own strengths and weaknessesand how you leverage these unique characteristics shapes the strategy you end up adopting the better you are at understanding trade-offsthe better you become at developing effective strategies the next step is to add one more character to the cast that can be generated by barracks for examplei am going to add an archer classbut feel free to add some of your own unit typesgiving them unique strengths and weaknesses you get to create your dream cast of units while you are at itfeel free to think of other attributes your units will need to add depth to the game when you are done with this go through the code you have written and add these ideas not only will it make your rts more interestingbut it will also help you better grasp the arguments presented throughout the with the addition of the archer classour rts_simple py now looks like thisrts_simple py class knight(object)def __init__selflifespeed |
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 lifeself speedself attack_powerself attack_rangeself weapon class archer(object)def __init__selflifespeedattack_powerattack_rangeweapon ) |
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 attack_rangeself weapon class barracks(object)def generate_knight(self)return knight( "short sword"def generate_archer(self)return archer( "short bow"if __name__ ="__main__"barracks barracks(knight barracks generate_knight(archer barracks generate_archer(print("[knight {}format(knight )print("[archer {}format(archer )nextyou will see the result of running this program we now have knight and an archereach with its very own unique values for the unit attributes read through the code and try to understand what each line is doing before you continue to the explanation of the results |
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 unit generatorit should be pretty clear that having separate function for each type of unit you plan on generating in specific building is not great idea to hammer this point home bitimagine what would happen if you wanted to upgrade the units that barracks could generate as an exampleconsider upgrading the archer class so that the weapon it gets created with is no longer short bow but rather long bowand its attack range is upped by five points along with two-point increase in attack power suddenlyyou double the number of functions needed in the barracks classand you need to keep some sort of record of the state of the barracks and the units that it can generate to make sure you generate the right level of unit alarm bells should be going off by now there must be better way to implement unit generationone that is aware of not only the type of unit you want it to generatebut also of the level of the unit in question one way to implement this would be to replace the individual generate_knight and generate_archer methods with one method called generate_unit this method would take as its parameters the type of unit to be generated along with the level of unit you wanted it to generate the single method would use this information to split out into the units to be created we should also extend the individual unit classes to alter the parameters used for the different unit attributesbased on level parameter passed to the constructor when the unit is instantiated |
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_range self weapon "long sworddef __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)self unit_type "archer |
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_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 ="archer"return archer(levelif __name__ ="__main__"barracks barracks( |
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 bewithout the need for the barracks class to keep track of every level of every unit and the relevant parameters associated with them [knight typeknight life speed attack power attack range weaponshort sword [archer typearcher life speed attack power attack range weaponlong bow like this implementation little more than the previous oneas we have reduced the methods needed and isolated the unit-level parameters inside the unit classwhere it makes more sense to have them in modern rts gamesbalance is big issue--one of the main challenges facing game designers the idea behind game balance is that sometimes users find way to exploit specific unit' characteristics in such way that it overpowers every other strategy or situation in the game even though that sounds like exactly the type of strategy you would want to findthis is actually guarantee that players will lose interest in your game alternativelysome characters might suffer from weakness that makes it practically useless for the game in both these casesthe unit in question (or the game as wholeis said to be imbalanced game designer wants to make alterations to the parameters of each unit (like attack powerin order to address these imbalances |
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 eve onlinewhich relies heavily on its python base for game logic we could store the parameters in separate json file or database to allow game designers to alter unit parameters in single place it would be easy to create nice gui (graphical user interfacefor game designers where they could quickly and easily make changes without even having to alter the file in text editor when we want to instantiate unitwe load the relevant file or entryextract the values we needand create the instance as beforelike thisknight_ dat short sword archer_ dat long bow rts_file_based py class knight(object)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[ |
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)self unit_type "archerfilename "{} {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[ |
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 ="archer"return archer(levelif __name__ ="__main__"baracks baracks(knight barracks build_unit("knight" archer barracks build_unit("archer" print("[knight {}format(knight )print("[archer {}format(archer )since the unit data files store the data in predictable orderit makes it very easy to grab the file from disk and then read in the parameters needed to construct the relevant unit the code still delivers the same result as beforebut now we are ready to balance many different unit types and levels in our examplethe import from file looks the same for both the archer and knight classesbut we must keep in mind that we will have units that have to import different parameters from their fileso single import file would be impractical in real-world scenario |
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 the levels and types of units that specific building can generate to change based on the level of the building level barracks generates only level knightsbut once the barracks is upgraded to level it unlocks the archer unitand as an added bonus it now generates level knights instead of the level knights from before upgrading one building only has an effect on the units that it is able to generateand not on the capabilities of all the buildings of the same type that the player built we cannot simply keep track of single instance of unitnow every building needs to track its own version of the unit every time building wants to create unitit needs to look up what units it can create and then issue command to create the selected unit the unit class then has to query the storage system to find the relevant parameterswhich are then read from storage before they are passed into the class constructor of the instance being created this is all very inefficient if one building has to generate units of the same typeyou have to make duplicate requests of the storage system you chose multiply this by the number of buildingsand then add the lookups each building needs to do to decide which units it should be capable of generating massive game like eve onlineor any other modern rts for that matterwill kill your system in short order if it is required to go through this process every time it needs to generate unit or build building some games take this step further by allowing specific add-ons on buildings that give units generated in that building different capabilities from the general unit typewhich would make the system even more resource hungry |
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 patternwe favor composition over inheritance classes that are composed of parts allow you to substitute those parts at runtimeprofoundly affecting the testability and maintainability of the system the classes to instantiate are specified at runtime by means of dynamic loading the result of this characteristic of the prototype pattern is that sub-classing is reduced significantly the complexities of creating new instance are hidden from the client all of this is greatbut the main benefit of this pattern is that it forces you to program to an interfacewhich leads to better design note just beware that deep-cloning classes with circular references can and will cause issues see the next section for more information on shallow versus deep copy we simply want to make copy of some object we have on hand to make sure the copy is set up the way it should beand to isolate the functionality of the object from the rest of the systemthe instance you are going to copy should provide the copying feature clone(method on the instance that clones the object and then modifies its values accordingly would be ideal the three components needed for the prototype pattern are as followsclient creates new object by asking prototype to clone itself prototype declares an interface for cloning itself concrete prototype implements the operation for cloning itself (credit for the tree components of the prototype pattern / /design-pattern-prototype/ |
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 remove the redundant calls from the equation this is also the point where the prototype design pattern deviates from the abstract factory design patternwhich we will look at later in this book by swapping the prototypes that building can use at runtimewe allow the building to dynamically switch to generating completely different units without any form of sub-classing of the building class in question our buildings effectively become prototype managers the idea of prototype pattern is greatbut we need to look at one more concept before we can implement the pattern in our buildings shallow copy vs deep copy python handles variables little differently than do other programming languages you may have come across apart from the basic typeslike integers and stringsvariables in python are closer to tags or labels than to the buckets other programming languages use as metaphor the python variables are essentially pointers to addresses in memory where the relevant values are stored let' look at the following examplea range( , print("[ {}format( ) print("[ {}format( ) append( print("[ {}format( )print("[ {}format( )the first statement points the variable to list of numbers from to (excluding nextvariable is assigned to the same list of numbers that is pointing to finallythe digit is added to the end of list pointed to by |
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 the same listit is clear that adding an element to the end of that list should show the element added to the end of the list no matter which variable you are looking at shallow copy when we want to make an actual copy of the listand have two independent lists at the end of the processwe need to use different strategy just as beforewe are going to load the same digits into list and point the variable at the list this timewe are going to use the slice operator to copy the list range( , print("[ {}format( ) [:print("[ {}format( ) append( print("[ {}format( )print("[ {}format( )the slice operator is very useful toolsince it allows us to cut up list (or stringin many different ways want to get all the elements from listwhile leaving out the first two elementsno problem--just slice the list with [ :what about all elements but the last twoslice does that[:- you could even ask the slice operator to only give you every second element challenge you to figure out how that is done when we assigned to [:]we told to point to slice created by duplicating the elements in list afrom the first to the last elementeffectively copying all the values in list to another location in memory and pointing the variable to this list |
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 think the result will belst [' '' '['ab''ba']lst lst [:lst [ 'cprint("[lst {}format(lst )print("[lst {}format(lst )hereyou see an example of deep list take look at the results--do they match what you predicted[lst [' '' '['ab''ba'][lst [' '' '['ab''ba']as you might have expected from the shallow copy examplealtering the first element of lst does not alter the first element of lst but what happens when we alter one of the elements in the list within the listlst [' '' '['ab''ba']lst lst [:lst [ ][ 'dprint("[lst {}format(lst )print("[lst {}format(lst )can you explain the results we get this time[lst [' '' '['ab'' '][lst [' '' '['ab'' '] |
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 the addresses for the element at position in lst were not clonedonly the value pointing to the position of the list ['ab''ba'in memory was as resultboth lst and lst ended up pointing to separate lists containing the characters 'aand 'bfollowed by pointer to the same list containing ['ab''ba']which would result in an issue whenever some function changes an element at this listsince it would have an effect on the contents of the other list deep copy clearlywe will need another solution when making clones of objects how can we force python to make complete copya deep copyof everything contained in the list and its sub-lists or objectsluckilywe have the copy module as part of the standard library the copy contains methoddeep-copythat allows complete deep copy of an arbitrary listi shallow and other lists we will now use deep copy to alter the previous example so we get the output we expect from copy import deepcopy lst [' '' '['ab''ba']lst deepcopy(lst lst [ ][ 'dprint("[lst {}format(lst )print("[lst {}format(lst )resulting in[lst [' '' '['ab''ba'][lst [' '' '['ab'' ']there now we have the expected resultand after that fairly long detourwe are ready to see what this means for the buildings in our rts |
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 any class that needs polymorphic constructor (the class decides which constructor to use based on the number of arguments it receives upon instantiationcapability derives itself from the abstract base class and implements the clone(method every unit needs to derive itself from this abstract base class the clientinstead of writing code that invokes the new operator on hard-coded class namecalls the clone(method on the prototype this is what the prototype pattern would look like in general termsprototype_ py from abc import abcmetaabstractmethod class prototype(metaclass=abcmeta)@abstractmethod def clone(self)pass concrete py from prototype_ import prototype from copy import deepcopy class concrete(prototype)def clone(self)return deepcopy(selffinallywe can implement our unit-generating building with the prototype patternusing the same prototype_ py file rts_prototype py from prototype_ import prototype from copy import deepcopy |
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__(self)return "type{ }\ "life{ }\ "speed{ }\ "attack power{ }\ "attack range{ }\ "weapon{ }formatself unit_typeself lifeself speedself attack_powerself attack_rangeself weapon def clone(self)return deepcopy(selfclass archer(prototype)def __init__(selflevel)self unit_type "archerfilename "{} {datformat(self unit_typelevel |
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_typeself lifeself speedself attack_powerself attack_rangeself weapon def clone(self)return deepcopy(selfclass barracks(object)def __init__(self)self units "knight" knight( ) knight( }"archer" archer( ) archer( |
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 unit classesthat forced us to implement the clone methodwhich we used when we had the barracks generate new units the other thing we did was generate all the options that barracks instance can generate and keep it in unit' array nowwe can simply clone the unit with the right level without opening file or loading any data from an external source [knight typeknight life speed attack power attack range weaponshort sword [archer typearcher life speed attack power attack range weaponlong bow well doneyou have not only taken your first steps to creating your very own rtsbut you have also dug deeply into very useful design pattern exercises take the prototype example code and extend the archer class to handle its upgrades experiment with adding more units to the barracks building |
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 own mini rts game with barracks and two units using pygame extend the clone method of each unit to generate random nameso each cloned unit will have different name |
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 the pygame package as our weapon of choice we will be creating factory classes factory classes define objects that take certain set of parameters and use that to create objects of some other class we will also define abstract factory classes that serve as the template used to build these factory classes etting started in virtual environmentyou can use pip to install pygame by using this commandpip install pygame this should be fairly painless nowto get an actual window to work withgraphic_base py import pygame pygame init(screen pygame display set_mode(( )save graphic_base py and run the filepython graphic_base py blank window that is pixels wide and pixels high will pop up on your screen and immediately vanish again congratulationsyou have created your first (cwessel badenhorst badenhorstpractical python design patterns |
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 suspends execution for given number of seconds ten-second sleep was added to the end of the scriptwhich keeps the window open for ten seconds before the script completes execution and the window vanishes was very excited when created window on screen the first timebut when called my roommate over to show him my windowhe was completely underwhelmed suggest you add something to the window before showing off your new creation extend graphic_base py to add square to the window graphic_base py import pygame import time pygame init(screen pygame display set_mode(( , )pygame draw rect(screen( )pygame rect( )pygame display flip(time sleep( the pygame draw rect function draws rectangle to the screen variable that points to your window the second parameter is tuple containing the color used to fill the shapeandlastlythe pygame rectangle is passed in with the coordinates of the top left and bottom right corners the three values you see in the color tuple make up what is known as the rgb value (for red green blue)and each component is value out of which indicates the intensity of the component color in the final color mix |
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 screen experiment with drawing different rectangles in many colors on screen the game loop the most basic concept in game programming is called the game loop the idea works like thisthe game checks for some input from the userwho does some calculation to update the state of the gameand then gives some feedback to the player in our casewe will just be updating what the player sees on the screenbut you could include sound or haptic feedback this happens over and over until the player quits every time the screen is updatedwe run the pygame display flip(function to show the updated display to the player the basic structure for game will then be as followssome initialization occurssuch as setting up the window and initial position and color of the elements on the screen while the user does not quit the gamerun the game loop when the user quitsterminate the window in codeit could look something like thisgraphic_base py import pygame window_dimensions screen pygame display set_mode(window_dimensionsplayer_quits false while not player_quitsfor event in pygame event get()if event type =pygame quitplayer_quits true pygame display flip( |
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 initial positionready to react to arrow key events shape_game py (see ch pyimport pygame window_dimensions screen pygame display set_mode(window_dimensionsx 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] - if pressed[pygame k_down] + if pressed[pygame k_left] - if pressed[pygame k_right] + screen fill(( )pygame draw rect(screen( )pygame rect(xy )pygame display flip(play around with the code for bit to see if you can get the block to not move out of the boundaries of the window now that your block can move around the screenhow about doing all of this for circleand then for triangle and now for game character icon you get the picturesuddenlythere is lot of display code clogging up the game loop what if we cleaned this up bit using an object-oriented approach to the situation |
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 rectscreen( )pygame rect(self xself class circle(shape)def draw(self)pygame draw circlescreen( )(selfxself ) |
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 pressed[pygame k_down]obj move('down'if pressed[pygame k_left]obj move('left'if pressed[pygame k_right]obj move('right'screen fill(( )obj draw(pygame display flip(since you now have the circle and square objects availablethink about how you would go about altering the program so that when you press the "ckey the object on screen turns into circle (if it is not currently onesimilarlywhen you press the "skey the shape should change to square see how much easier it is to use the objects than it is to handle all of this inside the game loop tip look at the keybindings for pygame together with the code in this there is still an improvement or two we could implementsuch as abstracting things like move and draw that have to happen with each class so we do not have to keep track of what shape we are dealing with we want to be able to refer to the shape in general and just tell it to draw itself without worrying about what shape it is (or if it is shapeto begin withand not some image or even frame of animation |
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 characteristics of good code as you try to come up with better way of handling the expansion we want to add to our shapeshifter game good code is easy to maintaineasy to updateeasy to extendand clear in what it is trying to accomplish good code should make working on something you wrote couple of weeks back as painless as possible the last thing you want is to create these areas in your code you dread working on we want to be able to create objects through common interface rather than spreading the creation code throughout the system this localizes the code that needs to change when you update the types of shapes that can be created since adding new types is the most likely addition you will make to the systemit makes sense that this is one of the areas you have to look at first in terms of code improvement one way of creating centralized system of object creation is by using the factory pattern this pattern has two distinct approachesand we will cover bothstarting with the simpler factory method and then moving on to the abstract factory implementation we will also look at how you could implement each of these in terms of our game skeleton before we get into the weeds with the factory patterni want you to take note of the fact that there is one main difference between the prototype pattern and the factory pattern the prototype pattern does not require sub-classingbut requires an initialize operationwhereas the factory pattern requires sub-classing but not initialization each of these has its own advantages and places where you should opt for one over the otherand over the course of this this distinction should become clearer |
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 functionality to your softwarewhich is accomplished by adding new class and extending the factory method to accept new string and return the class you created let' look at simple implementation of the factory method shape_ factory 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 + @staticmethod def factory(type)if type ="circle"return circle( if type ="square"return square( |
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"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 pressed[pygame k_down]obj move('down'if pressed[pygame k_left]obj move('left'if pressed[pygame k_right]obj move('right' |
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 matter to the user of the class whether new object is created or an old one recycled the idea is that you decouple the request for an object from its creation this idea should not be followed as dogmabut try it out in one of your own projects and see what benefits you derive from it once you are comfortable with using factory methodsand possibly factory patternsyou are free to use your own discretion in terms of the usefulness of the pattern in the project at hand whenever you add to your game new class that needs to be drawn on the screenyou simply need to change the factory(method what happens when we need different kinds of factoriesmaybe you would like to add sound effect factories or environmental elements versus player characters factoriesyou want to be able to create different types of factory sub-classes from the same basic factory the abstract factory when you want to create single interface to access an entire collection of factoriesyou can confidently reach for an abstract factory each abstract factory in the collection needs to implement predefined interfaceand each function on that interface returns another abstract typeas per the factory method pattern import abc class abstractfactory(object)__metaclass__ abc abcmeta @abc abstractmethod def make_object(self)return |
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 the concrete factories that then create circles and squares in this example python is dynamically typedso you do not need to define the common base class if we were to make the code more pythonicwe would be looking at something like thisclass circlefactory(abstractfactory)def make_object(self)do something return circle(class squarefactory(abstractfactory)def make_object(self)do something return square(def draw_function(factory)drawable factory make_object(drawable draw(def prepare_client()squarefactory squarefactory(draw_function(squarefactorycirclefactory circlefactory(draw_function(circlefactory |
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 elements of different operating systems all of them use the same basic functionsbut the factory that gets created gets selected based on the operating system the program is running on congratulationsyou just leveled up your ability to write great code using abstract factoriesyou can write code that is easier to modifyand code that can be tested easily summary when developing softwareyou want to guard against the nagging feeling that you should build something that will be able to cater to every possible future eventuality although it is good to think about the future of your softwareit is often an exercise in futility to try to build piece of software that is so generic that it will solve every possible future requirement the simplest reason for this is that there is no way to envision where your software will go ' not saying you should be naive and not consider the immediate future of your codebut being able to evolve your code to incorporate new functionality is one of the most valuable skills you will learn as software developer there is always the temptation to throw out all the old code you have previously written and start from scratch to "do it right that is dreamand as soon as you "do it rightyou will learn something new that will make your code look less than prettyand so you will have to redo everything againnever finishing anything the general principle is yagniyou will probably come across this acronym in your career as software developer what does it meanyou ain' gonna need itit is the principle that you should write code that solves the current problem welland only when needed alter it to solve subsequent problems this is why many software designs start out using the simpler factory methodand only once the developer discovers where more flexibility is needed does he evolve the program to use the abstract factoryprototypeor builder patterns |
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 the image when moving |
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 actuallymost applications are just special case of the inputtransformand feedback flow of information there are many input widgets and interfacesbut the most common remain the followingtext boxes dropdown and select lists checkboxes radio buttons file upload fields buttons these can be mixed and matched in many different ways to take different types of data as input from the user what we are interested in for this is how we can write script that could ease the effort of generating these forms for our use casewe will be generating html webformsbut the same technology can be usedwith couple of tweaksto generate mobile app interfacesjson or xml representations of the formor whatever else you can dream up let' begin by writing simple function that will generate little form for us (cwessel badenhorst badenhorstpractical python design patterns |
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 list of fields contains only text fields the field name is contained in the list as string the strings in the list are also the labels used in the form that is returned for every element in the lista single field is added to the webform the webform is then returned as string containing the html code for the generated webform if we go one step furtherwe could have script take the generated response and build regular html file from itone you could open in your web browser html_ form_ generator py def generate_webform(field_list)generated_fields "\njoinmaplambda '{ }:format( )field_list return "{fields}format(fields=generated_fieldsdef build_html_form(fields)with open("form_file html"was ff write"{}format(generate_webform(fields) |
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 we will add checkboxes html_ form_ generator py def generate_webform(text_field_list=[]checkbox_field_list=[])generated_fields "\njoinmaplambda '{ }:format( )text_field_list generated_fields +"\njoinmaplambda { }format( )checkbox_field_list return "{fields}format(fields=generated_fieldsdef build_html_form(text_field_list=[]checkbox_field_list=[])with open("form_file html"' 'as ff write"{}formatgenerate_webformtext_field_list=text_field_listcheckbox_field_list=checkbox_field_list |
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 defaults or options or in fact any information beyond simple label or field name we cannot even cater for difference between the field name and the label used in the form we are now going to extend the functionality of the formgenerator function so we can cater for large number of field typeseach with its own settings we also have the issue that there is no way to interleave different types of fields to show you how this would workwe are ripping out the named parameters and replacing them with list of dictionaries the function will look in each dictionary in the list and then use the contained information to generate the field as defined in the dictionary html_dictionary_ form_ generator py def generate_webform(field_dict_list)generated_field_list [for field_dict in field_dict_listif field_dict["type"="text_field"generated_field_list append'{ }:formatfield_dict["label"]field_dict["name"elif field_dict["type"="checkbox"generated_field_list append{ }formatfield_dict["id"]field_dict["value"]field_dict["label" |
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_text}"type""checkbox""id""check_it""value"" ""label""check for one"}"type""text_field""label""another text field""name""text_field build_html_form(field_listthe dictionary contains type fieldwhich is used to select which type of field to add thenyou have some optional elements as part of the dictionarylike labelnameand options (in the case of select listyou could use this as base to create |
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' generation code and place that into separate function that takes the dictionary and returns snippet of html code that represents that field the key in this step is to clean up the code without changing any of the functionalityinputor output of the main function cleaned_html_dictionary_ form_ generator py def generate_webform(field_dict_list)generated_field_list [for field_dict in field_dict_listif field_dict["type"="text_field"field_html generate_text_field(field_dictelif field_dict["type"="checkbox"field_html generate_checkbox(field_dictgenerated_field_list append(field_htmlgenerated_fields "\njoin(generated_field_listreturn "{fields}format(fields=generated_fieldsdef generate_text_field(text_field_dict)return '{ }:formattext_field_dict["label"]text_field_dict["name"def generate_checkbox(checbox_dict)return { }formatcheckbox_dict["id"]checkbox_dict["value"]checkbox_dict["label" |
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""another text field""name""text_field build_html_form(field_listthe if statements are still therebut at least now the code is little cleaner these sprawling if statements will keep growing as we add more field types to the form generator let' try to better the situation by using an object-oriented approach we could use polymorphism to deal with some of the specific fields and the issues we are having in generating them |
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"]kwargs["label"]def construct_text_field(selflabelfield_name)return '{ }:formatlabelfield_name def construct_checkbox(selffield_idvaluelabel)return { }formatfield_idvaluelabel def __str__(self)return self html def generate_webform(field_dict_list)generated_field_list [for field in field_dict_listtrygenerated_field_list append(str(htmlfield(**field))except exception as eprint("error{}format( ) |
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_name""field one}"field_type""checkbox""field_id""check_it""value"" ""label""check for on"}"field_type""text_field""label""another text field""field_name""field onebuild_html_form(field_listfor every alternative set of parameterswe need another constructorso our code very quickly breaks down and becomes mess of constructorswhich is commonly known as the telescoping constructor anti-pattern like design patternsanti-patterns are mistakes you will see regularly due to the nature of the software design and |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.