id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
8,200 | visitor pattern element status " : elif self person_ _homeelement status " : elsepass class compositevisitor(abstractvisitor)def __init__(selfperson_ _homeperson_ _home)self person_ _home person_ _home self person_ _home person_ _home def visit(selfelement)tryc eval("{}statusupdatevisitorformat (element __class__ __na... |
8,201 | visitor pattern doorlock("front door lock")coffeemachine("coffee machine")light("bedroom light")clock("system clock")]def test_person_ _not_home_person_ _not_home(self)expected_state mapstrself my_home_system iterable[ status'off' self my_home_system iterable[ status self visitor compositevisitor(falsefalseself my_home... |
8,202 | visitor pattern self visitor compositevisitor(truefalseself my_home_system accept(self visitorretrieved_state sorted([str( statusfor in self my_home_system iterable]self assertequal(retrieved_statesorted(expected_state)def test_person_ _not_home_person_ _home(self)expected_state mapstrself my_home_system iterable[ st... |
8,203 | visitor pattern self visitor compositevisitor(truetrueself my_home_system accept(self visitorretrieved_state sorted([str( statusfor in self my_home_system iterable]self assertequal(retrieved_statesorted(expected_state)if __name__ ="__main__"unittest main( have just couple of notes on the preceding code firstif you ar... |
8,204 | visitor pattern parting shots sometimes you just need to write codeso type out the example line by line to get feel for the idea expressed whenever find descriptions of an algorithm or idea that do not quite understand from the way it is describedi reach for this tool there is something different that happens when you... |
8,205 | visitor pattern exercises use the process from the "parting shotssection and code your way to deeper understanding of the visitor patternif you have not been doing so throughout the book find an interesting python package in the standard library and code through thatseeing how these developers do things differently fr... |
8,206 | model-view-controller pattern alwaysworlds within worlds --clive barkerweaveworld not far along in your journey as programmeryou begin to see some other patterns emerge--more like patterns of patterns like this one most if not all programs consist of some sort of external action that initiates the program the initiatin... |
8,207 | model-view-controller pattern seeing programs in this way helpssince you become better at asking questions about what happens at each step in the process sadlythis view is too general and leaves too much outand thus it is not completely helpful when it comes to the actual nuts and bolts development work stillit is usef... |
8,208 | model-view-controller pattern if __name__ ="__main__"main(sys argv[ ]the program uses the sys package in the standard library to expose the arguments passed to the program the first argument is the name of the script being executed in our example programthe first additional argument that is expected is the name of pers... |
8,209 | model-view-controller pattern write_name('names dat'namereturn "hi {}it is good to meet youformat(namedef main(name)print(get_message(name)if __name__ ="__main__"main(sys argv[ ] ' sure you suspect that there is more to come in terms of cleaning up this codeso why go through this process againthe reason for following t... |
8,210 | model-view-controller pattern return names def write_name(filenamename)with open(filenameget_append_write(filename)as data_filedata_file write("{}\nformat(name)def get_message(name)if name ="lion"return "rrrrrrrroar!if name_in_file('names dat'name)return "welcome back {}!format(namewrite_name('names dat'namereturn "hi ... |
8,211 | model-view-controller pattern command line the object in question is all about controlandunsurprisinglyobjects of this class are called controllers they are the glue that holds the system togetherand usually the place where the most action takes place here are the control functions from our previous program controller_... |
8,212 | model-view-controller pattern return 'wdef read_names(filename)with open(filename' 'as data_filenames data_file read(split('\ 'return names def write_name(filenamename)with open(filenameget_append_write(filename)as data_filedata_file write("{}\nformat(name)once the code is encapsulated into an objectyou will find that ... |
8,213 | model-view-controller pattern class genericcontroller(object)def __init__(self)self model genericmodel(self view genericview(def handle(selfrequest)data self model get_data(requestself view generate_response(datamodels models deal with datagetting datasetting dataupdating dataand deleting data that' it you will often ... |
8,214 | model-view-controller pattern the following is simple genericview class that you can use as base for building your own viewsbe they for returning json to an http call or plotting graphs for data analysis class genericview(object)def __init__(self)pass def generate_response(selfdata)print(databringing it all together f... |
8,215 | model-view-controller pattern def generate_response(selfdata)print(datadef main(name)request_handler genericcontroller(request_handler handle(nameif __name__ ="__main__"main(sys argv[ ]now that we have clear picture of what each of the object classes should look likelet' proceed to implement the code in our example for... |
8,216 | model-view-controller pattern nextwe create the model object that retrieves greeting from file or returns the standard greeting model py import os class namemodel(object)def __init__(self)self filename 'names datdef _get_append_write(self)if os path exists(self filename)return 'areturn 'wdef get_name_list(self)if not o... |
8,217 | model-view-controller pattern if knownprint("welcome back {}!format(name)elseprint("hi {}it is good to meet youformat(name)greatif you want to make requeststart the program like thispython controller py your_name the first time you run this scriptthe responseas expectedlooks like thishi your_nameit is good to meet you ... |
8,218 | model-view-controller pattern time_of_day=self time_model get_time_of_day()known=false view py class greetingview(object)def __init__(self)pass def generate_greeting(selfnametime_of_dayknown)if name ="lion"print("rrrrrrrroar!"return if knownprint("good {welcome back {}!format(time_of_dayname)elseprint("good {{}it is g... |
8,219 | model-view-controller pattern def save_name(selfname)with open(self filenameself _get_append_write()as data_filedata_file write("{}\nformat(name)class timemodel(object)def __init__(self)pass def get_time_of_day(self)time datetime datetime now(if time hour return "morningif <time hour return "afternoonif time hour > ret... |
8,220 | model-view-controller pattern solution would be to have the controller create the user instance and then force it to pass the user object to the constructor of the userprofile model class the same problems could arise on the view side of the picture the key thing to remember is that every object should have one respons... |
8,221 | model-view-controller pattern exercises swap out the view from the last implementation of the greeting program to display its output in graphical pop-upyou could look at pygame or pyqt for thisor any other graphics package available to you alter the model to read and write from and to json file rather than flat text f... |
8,222 | publish-subscribe pattern yelling is form of publishing --margaret atwood if you think back to the observer pattern we looked at in you will remember that we had an observable class and some observer classes whenever the observable object changed its state and was polled for changeit alerted all the observers registere... |
8,223 | publish-subscribe pattern def unregister(selfcallback)self callbacks discard(callbackdef unregister_all(self)self callbacks set(def poll_for_change(self)if self changedself update_all def update_all(self)for callback in self callbackscallback(selfalthough the observer pattern allows us to decouple the objects that are ... |
8,224 | publish-subscribe pattern the first step might seem trivialbut you will soon realize how simple it is to change the way you think about things by just changing what you call them class subscriber(object)def update(selfobserved)print("observing{}format(observed)class publisher(object)def __init__(self)self callbacks set... |
8,225 | publish-subscribe pattern class subscriber(object)def process(selfobserved)print("observing{}format(observed)class publisher(object)def __init__(self)self subscribers set(def subscribe(selfsubscriber)self subscribers add(subscriberdef unsubscribe(selfsubscriber)self subscribers discard(subscriberdef unsubscribe_all(sel... |
8,226 | publish-subscribe pattern class publisher(object)def __init__(self)self subscribers set(def subscribe(selfsubscriber)self subscribers add(subscriberdef unsubscribe(selfsubscriber)self subscribers discard(subscriberdef unsubscribe_all(self)self subscribers set(def publish(selfmessage)for subscriber in self subscriberssu... |
8,227 | publish-subscribe pattern def publish(selfmessage)self dispatcher send(messageclass dispatcher(object)def __init__(self)self subscribers set(def subscribe(selfsubscriber)self subscribers add(subscriberdef unsubscribe(selfsubscriber)self subscribers discard(subscriberdef unsubscribe_all(self)self subscribers set(def sen... |
8,228 | publish-subscribe pattern class publisher(object)def __init__(selfdispatcher)self dispatcher dispatcher def publish(selfmessage)self dispatcher send(messageclass dispatcher(object)def __init__(self)self topic_subscribers dict(def subscribe(selfsubscribertopic)self topic_subscribers setdefault(topicset()add(subscriberde... |
8,229 | publish-subscribe pattern distributed message sender sending messages from many machines now that we have arrived at clean implementation of the pubsub patternlet' use the ideas we have developed so far to build our own simple message sender for thiswe are going to use the socket package from the python standard libra... |
8,230 | publish-subscribe pattern self subscribers self topic_subscribers[topicset(return "okdef send(selfmessage)print("sending message:\ntopic{}\npayload{}format(message["topic"]message["payload"])for subscriber in self topic_subscribers [message get("topic""all")]with serverproxy(subscriberas subscriber_proxysubscriber_pr... |
8,231 | publish-subscribe pattern subscriber py from xmlrpc client import serverproxy from xmlrpc server import simplexmlrpcserver class subscriber(simplexmlrpcserver)def __init__(selfdispatchertopic)super(subscriberself__init__(("localhost" )print("listening on port "self register_function(self process"process"self subscribe(... |
8,232 | publish-subscribe pattern window publisher python publisher py with each of the windows running its processlet' enter message into the publisher window and see what happens we see the dispatcher received the message and sent it to the subscriber listening on port subscribing [ /aug/ : : "post /rpc http/ sending message... |
8,233 | publish-subscribe pattern as jocko willink (navy seal commander task unit bruserlikes to saydiscipline equals freedom the discipline you apply to your coding practice will lead to freedom from the pain of maintaining cumbersome systems you will also avoid the inevitable dump and rewrite that most software products head... |
8,234 | design pattern quick reference quick checks for the code singleton pattern prototype pattern factory pattern builder pattern adapter pattern decorator pattern facade pattern proxy pattern chain of responsibility pattern composite command pattern interpreter pattern iterator pattern observer pattern state pattern strate... |
8,235 | design pattern quick reference template method pattern visitor pattern model-view-controller pattern publisher-subscriber pattern singleton singleton py class singletonobject(object)class __singletonobject()def __init__(self)self val none def __str__(self)return "{ ! { }format(selfself valthe rest of the class definit... |
8,236 | design pattern quick reference prototype prototype_ 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(selffactory factory py import ... |
8,237 | design pattern quick reference builder form_builder py from abc import abcmetaabstractmethod class director(objectmetaclass=abcmeta)def __init__(self)self _builder none @abstractmethod def construct(self)pass def get_constructed_object(self)return self _builder constructed_object class builder(objectmetaclass=abcmeta)d... |
8,238 | design pattern quick reference adapter third_party py class whatihave(object)def provided_function_ (self)pass def provided_function_ (self)pass class whatiwant(object)def required_function()pass adapter py from third_party import whatihave class objectadapter(object)def __init__(selfwhat_i_have)self what_i_have what_i... |
8,239 | design pattern quick reference @dummy_decorator def do_nothing()print("inside do_nothing"if __name__ ="__main__"print("wrapped function",do_nothing __name__do_nothing(facade simple_ facade py class invoicedef __init__(selfcustomer)pass class customeraltered customer class to try to fetch customer on init or creates ne... |
8,240 | design pattern quick reference proxy proxy py import time class rawclass(object)def func(selfn)return (ndef memoize(fn)__cache {def memoized(*args)key (fn __name__argsif key in __cachereturn __cache[key__cache[keyfn(*argsreturn __cache[keyreturn memoized class classproxy(object)def __init__(selftarget)self target targe... |
8,241 | design pattern quick reference chain of responsibility chain_of_responsibility py class endhandler(object)def __init__(self)pass def handle_request(selfrequest)pass class handler (object)def __init__(self)self next_handler endhandler(def handle_request(selfrequest)self next_handler handle_request(requestdef main(reques... |
8,242 | design pattern quick reference command command py class commanddef __init__(selfreceivertext)self receiver receiver self text text def execute(self)self receiver print_message(self textclass receiver(object)def print_message(selftext)print("message received{}format(text)class invoker(object)def __init__(self)self comma... |
8,243 | design pattern quick reference composite composite py class leaf(object)def __init__(self*args**kwargs)pass def component_function(self)print("leaf"class composite(object)def __init__(self*args**kwargs)self children [def component_function(self)for child in childrenchild component_function(def add(selfchild)self childr... |
8,244 | design pattern quick reference iterator classic_iterator py import abc class iterator(metaclass=abc abcmeta)@abc abstractmethod def has_next(self)pass @abc abstractmethod def next(self)pass class container(metaclass=abc abcmeta)@abc abstractmethod def getiterator(self)pass class mylistiterator(iterator)def __init__(sel... |
8,245 | design pattern quick reference if __name__ ="__main__"my_list mylist( my_iterator my_list getiterator(while my_iterator has_next()print(my_iterator next()alternative iterator_alt py for element in collectiondo_something(elementobserver observer py class concreteobserver(object)def update(selfobserved)print("observing{}... |
8,246 | design pattern quick reference def poll_for_change(self)if self changedself update_all def update_all(self)for callback in self callbackscallback(selfstate state py class state(object)pass class concretestate (state)def __init__(selfstate_machine)self state_machine state_machine def switch_state(self)self state_machine... |
8,247 | design pattern quick reference def __str__(self)return str(self statedef main()state_machine statemachine(print(state_machinestate_machine switch(print(state_machineif __name__ ="__main__"main(strategy strategy py def executor(arg arg func=none)if func is nonereturn "strategy not implemented return func(arg arg def str... |
8,248 | design pattern quick reference @abc abstractmethod def _step_ (self)pass @abc abstractmethod def _step_ (self)pass @abc abstractmethod def _step_ (self)pass class concreteimplementationclass(templateabstractbaseclass)def _step_ (self)pass def _step_ (self)pass def _step_ (self)pass visitor visitor py import abc class v... |
8,249 | design pattern quick reference class abstractvisitor(object)__metaclass__ abc abcmeta @abc abstractmethod def visit(selfelement)raise notimplementederror(" visitor need to define visit method"class concretevisitable(visitable)def __init__(self)pass class concretevisitor(abstractvisitor)def visit(selfelement)pass model... |
8,250 | design pattern quick reference class genericview(object)def __init__(self)pass def generate_response(selfdata)print(datadef main(name)request_handler genericcontroller(request_handler handle(nameif __name__ ="__main__"main(sys argv[ ]publisher-subscriber publish_subscribe py class message(object)def __init__(self)self ... |
8,251 | design pattern quick reference class dispatcher(object)def __init__(self)self topic_subscribers dict(def subscribe(selfsubscribertopic)self topic_subscribers setdefault(topicset()add(subscriberdef unsubscribe(selfsubscribertopic)self topic_subscribers setdefault(topicset()discard(subscriberdef unsubscribe_all(selftopic... |
8,252 | abstract base class (abc) adapter pattern class adapter don' repeat yourself duck typing implementation mail_sender py object parting shots problem send_email py separation of concern users csv file barracks builder pattern abstraction anti-patterns basic_form_generator py cleaned_html_dictionary_form_ generator py cou... |
8,253 | table of contents about the tutorial audience prerequisites copyright disclaimer table of contents ii python design patterns introduction structure of design pattern why python python design patterns gist of python features of python language important points how to download python language in your system the important... |
8,254 | how to implement the command pattern python design patterns adapter pattern how to implement the adapter pattern python design patterns decorator pattern how to implement decorator design pattern python design patterns proxy pattern how to implement the proxy pattern python design patterns chain of responsibility patte... |
8,255 | python design pattern the lists data structure how to implement lists python design patterns sets how to implement sets python design patterns queues how to implement the fifo procedure how to implement the lifo procedure what is priority queue python design patterns strings and serialization python design patterns con... |
8,256 | python design patterns introduction design patterns are used to represent the pattern used by developers to create software or web application these patterns are selected based on the requirement analysis the patterns describe the solution to the problemwhen and where to apply the solution and the consequences of the i... |
8,257 | participants and consequences participants include classes and objects that participate in the design pattern with list of consequences that exist with the pattern why pythonpython is an open source scripting language it has libraries that support variety of design patterns the syntax of python is easy to understand an... |
8,258 | patterns help to achieve communication and maintain well documentation it includes record of accomplishment to reduce any technical risk to the project design patterns are highly flexible to use and easy to understand |
8,259 | python design patterns gist ofpython python python is an open source scripting languagewhich is high-levelinterpretedinteractive and object-oriented it is designed to be highly readable the syntax of python language is easy to understand and uses english keywords frequently features of python language in this sectionwe... |
8,260 | it includes high-level dynamic data types and supports various dynamic type checking python includes feature of integration with cc+and languages like java |
8,261 | how to download python language in your systemto download python language in your systemfollow this linkit includes packages for various operating systems like windowsmacos and linux distributions the important tools in python in this sectionwe will learn in brief about few important tools in python python strings the ... |
8,262 | python dictionary python dictionary is type of hash table dictionary key can be almost any data type of python the data types are usually numbers or strings tinydict {'name''omkar','code': 'dept''sales'what constitutes design pattern in pythonpython helps in constituting design pattern using the following parameterspat... |
8,263 | python design patterns model view controller pattern model view controller is the most commonly used design pattern developers find it easy to implement this design pattern following is basic architecture of the model view controllerlet us now see how the structure works model it consists of pure application logicwhich... |
8,264 | view represents the html fileswhich interact with the end user it represents the model' data to user controller it acts as an intermediary between view and model it listens to the events triggered by view and queries model for the same python code let us consider basic object called "personand create an mvc design patt... |
8,265 | view it displays all the records fetched within the model view never interacts with modelcontroller does this work (communicating with model and viewfrom model import person def showallview(list)print 'in our db we have % users here they are:len(listfor item in listprint item name(def startview()print 'mvc the simplest... |
8,266 | return view endview(if __name__ ="__main__"#running controller function start( |
8,267 | python design patterns singleton pattern this pattern restricts the instantiation of class to one object it is type of creational pattern and involves only one class to create methods and specified objects it provides global point of access to the instance created how to implement singleton classthe following program d... |
8,268 | return singleton __instance def __init__(self)""virtually private constructor ""if singleton __instance !noneraise exception("this class is singleton!"elsesingleton __instance self singleton(print singleton getinstance(print singleton getinstance(print output the above program generates the following output |
8,269 | the number of instances created are same and there is no difference in the objects listed in output |
8,270 | python design patterns factorypython pattern the factory pattern comes under the creational patterns list category it provides one of the best ways to create an object in factory patternobjects are created without exposing the logic to client and referring to the newly created object using common interface factory patt... |
8,271 | "forces"some richcomplex subsystem offers lot of useful functionalityclient code interacts with several parts of this functionality in way that' "out of controlthis causes many problems for client-code programmers and subsystem ones too (complexity rigidity |
8,272 | interpose simpler "facadeobject/class exposing controlled subset of functionality dp "facadeclient code now calls existing supplier code provides ric into the facadeonly complex functionality in protocol the facade implements we need simpler "subsetc of facade code implements and supp its simpler functionality (by call... |
8,273 | summary of frequent design problem structure of solution to that problem (pros and consalternatives)anda name (much easier to retain/discuss!"descriptions of communicating objects and classes customized to solve general design problem in particular contextthat' nota data structurealgorithmdomain-specific system archite... |
8,274 | in the python standard library dbhash facades for bsddb highly simplified/subset access also meets the "dbminterface (thusalso an example of the adapter dpos pathbasenamedirname facade for split indexingisdir (&cfacade for os stat stat s_isdir (&cfacade is structural dp (we'll see anotheradapterlaterin dbhashthey "merg... |
8,275 | |
8,276 | summary of frequent design problem structure of solution to that problem pros and consalternativesanda name (much easier to retain/discuss!"descriptions of communicating objects and classes customized to solve general design problem in particular contextdps are notdata structuresalgorithmsdomain-specific system archite... |
8,277 | (biblio on the last slide |
8,278 | creationalways and means of object instantiation structuralmutual composition of classes or objects (the facade dp is structuralbehavioralhow classes or objects interact and distribute responsibilities among them each can be class-level or object-level |
8,279 | "program to an interfacenot to an implementationthat' mostly done with "duck typingin python -rarely /"formalinterfaces actually similar to "signature-based polymorphismin +templates |
8,280 | teaching the ducks to type takes whilebut saves you lot of work afterwards!- |
8,281 | "favor object composition over class inheritancein pythonholdor wrap inherit only when it' really convenient expose all methods in base class (reuse usually override maybe extendbutit' very strong coupling |
8,282 | |
8,283 | "hold"object has subobject as an attribute (maybe property-that' all use self method or method simpledirectimmediatebut pretty strong couplingoften on the wrong axis holder holdee client |
8,284 | "wrap"hold (often via private nameplus delegation (so you directly use methodexplicit (def method(self self methodautomatic (delegation in __getattr__gets coupling right (law of demeterwrapper wrappee client |
8,285 | class restrictingwrapper(object)def __init__(selfwblock)self _w self _block block def __getattr__(selfn)if in self _blockraise attributeerrorn return getattr(self _wninheritance cannot restrict |
8,286 | not very common in python because "factoryis essentially built-in!- |
8,287 | "we want just one instance to existuse module instead of class no subclassingno special methodsmake just instance (no enforcementneed to commit to "whento make it singleton ("highlander"subclassing not really smooth monostate ("borg"guido dislikes it |
8,288 | class singleton(object)def __new__(cls* ** )if not hasattr(cls'_inst')cls _inst super(singletoncls __new__(cls* **kreturn cls _inst subclassing is problemthoughclass foo(singleton)pass class bar(foo)pass foo() bar()??problem is intrinsic to singleton |
8,289 | class borg(object)_shared_state {def __new__(cls* ** )obj super(borgcls __new__(cls* **kobj __dict__ cls _shared_state return obj subclassing is no problemjustclass foo(borg)pass class bar(foo)pass class baz(foo)_shared_state {data overriding to the rescue |
8,290 | "we don' want to commit to instantiating specific concrete class"dependency injectiondp no creation except "outsidewhat if multiple creations are needed"factorysubcategory of dps may create /ever or reuse existing factory functions (other callablesfactory methods (overridableabstract factory classes |
8,291 | "masquerading/adaptationsubcategoryadaptertweak an interface (both class and object variants existfacadesimplify subsystem' interface and many others don' coversuch asbridgemany implementations of an abstractionmany implementations of functionalityno repetitive coding decoratorreuse+tweak / inheritance proxydecouple fr... |
8,292 | client code requires protocol supplier code provides different protocol (with superset of ' functionalityadapter code "sneaks in the middle"to ga is supplier (produces protocol cto sa is client (consumes protocol "inside" implements (by means of appropriate calls to on |
8,293 | requires method foobar(foobars supplies method barfoo(barfooe could beclass barfooer(object)def barfoo(selfbarfoo) |
8,294 | per-instancewith wrapping delegationclass foobarwrapper(object)def __init__(selfwrappee)self wrappee def foobar(selffoobar)return self barfoo(barfoofoobarer=foobarwrapper(barfooer |
8,295 | per-classw/subclasing self-delegationclass foobarer(barfooer)def foobar(selffoobar)return self barfoo(barfoofoobarer=foobarerw/ever |
8,296 | flexiblegood use of multiple inheritanceclass bf fbdef foobar(selffoobar)return self barfoo(barfooclass foobarer(bf fbbarfooer)pass foobarer=foobarerw/ever |
8,297 | socket _fileobjectfrom sockets to file-like objects ( /much code for bufferingdoctest doctestsuiteadapts doctest tests to unittest testsuite dbhashadapt bsddb to dbm stringioadapt str or unicode to file-like shelveadapt "limited dict(str keys and valuesbasic methodsto complete mapping via pickle for any string userdict... |
8,298 | some rl adapters may require much code mixin classes are great way to help adapt to rich protocols (implement advanced methods on top of fundamental onesadapter occurs at all levels of complexity in pythonit' _not_ just about classes and their instances (by long shot!--often _callables_ are adapted (via decorators and ... |
8,299 | adapter' about supplying given protocol required by client-code orgain polymorphism via homogeneity facade is about simplifying rich interface when just subset is often needed facade most often "frontsfor subsystem made up of many classes/objectsadapter "frontfor just one single object or class |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.