A brief analysis of Python design pattern

Source: Internet
Author: User

Today's brief talk about Python's design pattern, gof design pattern (c + +) and head first design pattern (Java) are classic in two designs, and can be copied to Python, but you'll find that Python has a lot of its own stuff, For example, it doesn't have multiple constructors, and it has classmethod, so python design patterns are worth talking about.

constructor function:

Python2:

class Person (object):     def __init__ (self, name):         = Name

Python3:

class Person :     def __init__ (self, name):         = Name

You do not need to use New,person = Person ("Xiaozhang") when calling. All classes are inherited from object and Python2 need to be explicit and python3 to help you get it done. Inheritance and object have many benefits, and one benefit is super (). Python3 can call the method of the parent class directly through Super (). Parent_method () Python2 requires super (subclass name, self). Parent_method ()

Inherited
 class   Animal:  def  __init__   (self, name): Self.name  = name  class   Dog (Animal):  pass  class   Cat (Animal):  pass  
>>> animal = Dog ("Dodo")>>> animal.name' Dodo '>>> isinstance (animal, animal) True>>> isinstance (Animal, Dog) True >>> isinstance (Animal, Cat) False

Isinstance can be used to check object types.

Override
>>>classAnimal: ... sound=""...     defSpeak (self): ...Print("The animal says:"+self.sound) ...>>>classDog (Animal): ... sound="wangwang!"... >>>classCat (Animal): ... sound="Miaomiao"... >>>classTurtle (Animal): ...Pass... >>>Dog (). Speak () The animal says:wangwang!>>>Cat (). Speak () The animal Says:miaomiao>>>Turtle (). Speak () The animal says:

Python does not support method overloading, some languages such as C++,java can define multiple functions with the same name as long as the parameter type is different, Python can not, later defined will overwrite the previously defined method if there are multiple methods with the same name.

Private type

Python does not have access control, and the habit is to use self._something to indicate that this thing is private please do not get it directly, however you can take it casually.

You can also use __,python to mangle this variable __something to _classname__something, and if you know this layer name mangling you can still get it.

Read only for design mode

Python has a decorator called a property, the method of adding to it, can only read, cannot write. If you want to write, add the decorate method name. Setter. Some input check can be done in the setter. With the property we can creatively refactor some classes.

The Pub-sub of design pattern
ImportOSImport TimeclassFilewatcher (object):def __init__(self, path_of_file_to_watch): Self.path=Path_of_file_to_watch self.observers=set ()defregister (self, name): Self.observers.add (name)defUnregister (self, name): Self.observers.discard (name)defNotify (self, message): forIinchself.observers:i.update (message)classFileobserver (object):def __init__(self, name): Self.name=namedefUpdate (self, message):Print "%s noticed that the file was now%d bytes"%(self.name, message) filename="/tmp/test.txt"F=filewatcher (filename) Bob= Fileobserver ("Bob") John= Fileobserver ("John") Stacy= Fileobserver ("Stacy") F.register (Bob) F.register (John) F.register (Stacy) Init_size=os.stat (filename). st_size whileTrue:ifOs.stat (filename). st_size! =init_size:f.notify (os.stat (filename). st_size) Init_size=os.stat (filename). st_size Time.sleep (1)
Classmethod mode
def __init__ (self, something):     @classmethoddef  Some_alternative_constructor (CLS, some_other_thing):    * * * = some_other_thing balbla    return cls (something)     

Use the class name directly when calling. Another constructor that returns the desired object. Applies directly to subclasses.

Staticmethod

Equivalent to the definition function, without self, CLS, equivalent to write function directly, and then can be called directly with the class name.

A brief analysis of Python design pattern

Related Article

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.