Python advanced point of Use, Monkey patch with meta class

Source: Internet
Author: User

Long time no update, today think about what to record, the decorator what do not say, very familiar with the record.

1.monkey Patch.

is actually a way of dynamically modifying classes, including property methods.

For example A = a () A.foo = foo and the like, but how to modify before running, like Gevent, with their own socket to replace,

Gevent source code is like this

from eventlet.green import socketpatcher.inject (' Ftplib ', Globals (), (' socket ', socket)) 

then inject sys.modules[ ' __patched_module_ ' + module_name] = module this key statement.
that is, if you want to implement such a uniform entry patch, you need to understand how python looks for variables, LEGB that is, when Python loads the module, sys.modules loads it and then adds it to the current module according to the LEGB principle
Here is a practical example, if one day the product needs to implement a common function in all search interface, such as remembering the current page alive search results, jump back will also have, the page involves dozens of or even hundreds, how to do it, of course, a hungry a change also extinguished problems,
but this change of workload, and error prone, Test the coverage point, the period will be very long, so you can look at the following
def _wraper (FN):
def _render (*args, **kwagrs):
Request = Args[0]
Http_content = args[2]
page = Request. Get.get (' Dt_page ', 0)
Try
page = Int (page)
Except
page = 0
Http_content.update ({' Dt_page ': page})
RETURN fn (*args, **kwagrs)
Return _render
__import__ ("Django.shortcuts")
SYS = __import__ ("sys")
_render_module = sys.modules[' django.shortcuts ']
_render_module.render = _wraper (_render_module.render)
Because each page is rendered through a page, it is loaded directly into
Django.shortcuts and modify its Render method into its own decoration in the render, of course, I just added a dt_page parameter, in the front-end click on the parameters, of course, the front end is similar, is in JS and the page after the completion of loading,
Use the Dom.find selector and then modify all the links and add dt_page parameters to achieve the effect, haha is not very magical. This is Monkeypatch, Gevent is also the way to replace the system socket library.
Here's another way to dynamically modify a class.
2. Meta-class
This is more complicated, I just understand, actually and BAA use, in fact, Django Orm is the use of meta-class to achieve.
In fact, to understand this, the direct look is too abstract. Let's say it separately.
1) First chicken or egg, object and type
    • The object class is the parent class for all modern classes.

    • Type is a class of all classes

Of course, the relationship between object itself and type may be blurred:

>>> object.__class__
<type ' type ' >
>>> object.__bases__ # object has no parent class because it is the top of the chain.
()
-Type is an object, type is kind of object. That is, the type is a subclass of object.

>>> type.__bases__
(<type ' object ';,)
>>> type.__class__ # type is its own
<type ' type ' >

So in the Python world, object is the top of the parent-child relationship, all of the data types are the parent class, and type is the top of the type instance relationship, and all the objects are instances of it.

That is, the class itself is an instance, and it relies on the type to generate the class power, unlike other compiled languages java,c#, because they have only object but no type class, so they cannot implement dynamic modification classes.

Of course, the meta-class of the classic class is generated by inheriting the class classobj of type, and the new class (inheriting object) is generated by type (if you do not specify the meta-class manually). With this, presumably we all know why you can use meta-class to modify class. OK, here's a try, custom meta-class.

2) First there is a very simple way to generate a class, directly with type,

Foo = type (' foo ', (), {}) so that a Foo class can be generated directly. In fact, it is equivalent to using type to generate a Foo class, with the meaning of class Foo, but usually not so. How do we change it dynamically? With

Keyword __metaclass__ can specify which class to use to create the current class,

Class Mymetaclass (Type):

def __new__ ( cls , name, bases, dct ):

Class MyClass (object):

__metaclass__ = Mymetaclass

Pass

This creates the MyClass is created by the Mymetaclass, in the Mymetaclass can modify the class you want to create, so that the understanding is not so abstract, the parameters inside the API to understand, time in check.



 

Python advanced point of Use, Monkey patch with meta class

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.