Python advanced Programming: useful Design Patterns 3

Source: Internet
Author: User

#-*-Coding:utf-8-*-
__author__ = ' Administrator '
#python高级编程: A useful design pattern
#访问者: Helps isolate the algorithm from the data structure
"""
It has a similar goal to the observer, and can extend the specified class functionality without modifying the code, but the visitor further, it will define a responsibility to save the data class, and push the algorithm into other classes called visitors.
This behavior is quite similar to the MVC scope (see: Http://en.wikipedia.org/wiki/model-view-controller), in which the document is a passive container.
Push to view via controller, mode will contain data modified by controller
A visitor does this by providing an entry point in the data class that can be accessed by all types of visitors: a visitable class that accepts visitor instances and calls them:.

The Visitable class determines how to invoke the Visitor class, for example, deciding which method to invoke, for example, a visitor responsible for printing the content of the built-in type can implement
The Visit_typename method, in which each type can invoke the specified method in its Accpet method, is as follows:
"""

Class Visit (list):
def accept (Self,visitor):
Visitor.visit_list (self)

Class Vdict (Dict):
def accept (Self,visitor):
Visitor.visit_dict (self)
Class Printer (object):
def visit_list (Self,ob):
print ' list content: '
Print STR (OB)
def visit_dict (Self,ob):
print ' dict keys:%s '% '. Join (Ob.keys ())

A_list=visit ([1,2,5])
A_list.accept (Printer ())
A_dict=vdict ({' One ': 1, ' both ': 2, ' Three ': 3})
A_dict.accept (Printer ())
"""
But this means that every class visited must have an accept method, which is painful
Because Python allows introspection, it is a better idea to automatically link the visitor and the visitor class, as follows:
"""
def visit (V1,V2):
cls=v1.__class__.__name__
Ment= ' visit%s '%cls
Methond=getattr (V2,MENT,CLS)
If ment is None:
ment (v1)

Visit ([1,2,5],printer ())
Visit ({' One ': 1, ' One ': 2, ' three ': 3},printer ())
"""
For example, this pattern is called in this way in the Compiler.visitor module, and the Astvisitor class invokes each node of the compiled code tree to invoke the visitor, because
Python does not have a matching operator, such as haskell!
Another example is the traversal of a program based on the purpose of calling the accessor method according to the file extension, as follows:
"""
Import OS
def visit1 (DIR1,V1):
For Root,dirs,files in Os.walk (DIR1):
For file in Files:
Ext=os.path.splitext (file) [ -1][1:]
If Hasattr (v1,ext):
GetAttr (v1,ext) (file)

Class FileRead (object):
def PADF (self,files):
print ' processing%s '%files

Walker=visit1 (R '/', FileRead ())
"""
If your application has data structures that are accessed by multiple algorithms, then the visitor pattern will help distract you: for a data container, it's better to focus on providing data access and storage capabilities, regardless of the others.
A good practice is to create a data structure without any method, just like a struct in C.
"""
#模板: Help developers design common algorithms by defining abstract steps (implemented in subclasses).
"""
Template mode uses the Liskov substitution principle:
If S is a subtype of T, objects of type T in the program can be replaced with objects of type S instead of needing to modify any of the required properties in the program (Wikipedia)

In other words: An abstract class can define an algorithm to implement steps in a specific class, and this abstract class can also give a basic or partial implementation of the algorithm, allowing the developer to reload its parts
Through the text indexing program, as follows:

Text Normalization
Text splitting
Delete useless words
Extracting stemming
Frequency count

Indexer provides the implementation of the processing algorithm section, but requires the implementation of _remove_stop_words and _setm_words methods in subclasses
Basicindex implements the most small portion, while Locallndex uses a useless word file and a stemming database, Fastindexer implements all the steps and may be based on fast indexing such as Xapian or Lucene, for example:
"""

Class Indexer (object):
def process (Self,text):
Text=self._normali_text (text)
Words=self._split_text (text)
Word=self._remove_stop_words (words)
Setemmed_words=self._stem_words (words)
Return Self._frequency (Setemmed_words)
def _normali_text (Self,text):
Return Text.lower (). Strip ()
def _split_text (Self,text):
Return Text.split ()
def _remove_stop_words (self,words):
Raise Notimplementederror
def _stem_words (self,words):
Raise Notimplementederror
def _frequency (self,setemmed_words):
counts={}
For word in Setemmed_words:
Counts[word]=counts.get (word,0) +1
#BasicIndex实现如下:
From Itertools import GroupBy
Class Basicindex (Indexer):
_stop_words= (' He ', ' she ', ' is ', ' and ', ' or ')
def _remove_stop_words (self,words):
return (word for word in words if Word is not in self._stop_words)
def _stem_words (self,words):
Return ((Len (word) >2 and Word.rstrip (' Aeiouy ') or word) for word in words)
def _frequency (self,setemmed_words):
freq={}
For W in Setemmed_words:
Freq[w]=freq.get (w,0) +1

Index=basicindex ()
Index.process (' My tailor is rich and he isx also my friend ')
"""
For algorithms that may vary and can express independent sub-steps, you should consider template patterns
Python has a book, is GOF design mode <python cookbook>: (Http://aspn.activestate.com/aspn/python/cookbook)
"""

Python advanced Programming: useful Design Patterns 3

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.